Sending messages from SharedWorker to SharedWorker - javascript

The MDN Documentation on SharedWorkers states:
The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers.
To me this sounds as if SharedWorkers should be able to directly exchange messages. However, if I try to access a SharedWorker from within another SharedWorker, namely with
var worker = new SharedWorker("path/to/file.js");
I get
ReferenceError: SharedWorker is not defined
Did I just misread the documentation, or is there another way to do this?

Although you don't seem to be able to create a shared worker from a shared worker, you can communicate between them by creating them in the main thread, and passing the MessagePort object of one to the other. Note you have to include the port in the transfer list argument to postMessage: it can't be copied.
For example, in the main thread create the workers, and send the port of one to the other:
var myWorker1 = new SharedWorker("worker1.js");
myWorker1.port.start();
var myWorker2 = new SharedWorker("worker2.js");
myWorker2.port.start();
myWorker2.port.postMessage({worker1Port: myWorker1.port}, [myWorker1.port]);
In the first worker you can send messages on a port:
self.onconnect = function(e) {
var port = e.ports[0];
self.setInterval(function() {
port.postMessage('sent from worker 1');
}, 1000);
};
and then in the second worker you can save the incoming port object, and respond to messages received on it.
self.onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
var worker1Port = e.data.worker1Port;
worker1Port.onmessage = function(e) {
console.log('received in worker 2', e.data);
};
};
};
You can see this working at http://plnkr.co/edit/XTOej1b1PHfWuC9LHeZc?p=preview

Related

WebSocket needs browser refresh to update list

My project works as intended except that I have to refresh the browser every time my keyword list sends something to it to display. I assume it's my inexperience with Expressjs and not creating the route correctly within my websocket? Any help would be appreciated.
Browser
let socket = new WebSocket("ws://localhost:3000");
socket.addEventListener('open', function (event) {
console.log('Connected to WS server')
socket.send('Hello Server!');
});
socket.addEventListener('message', function (e) {
const keywordsList = JSON.parse(e.data);
console.log("Received: '" + e.data + "'");
document.getElementById("keywordsList").innerHTML = e.data;
});
socket.onclose = function(code, reason) {
console.log(code, reason, 'disconnected');
}
socket.onerror = error => {
console.error('failed to connect', error);
};
Server
const ws = require('ws');
const express = require('express');
const keywordsList = require('./app');
const app = express();
const port = 3000;
const wsServer = new ws.Server({ noServer: true });
wsServer.on('connection', function connection(socket) {
socket.send(JSON.stringify(keywordsList));
socket.on('message', message => console.log(message));
});
// `server` is a vanilla Node.js HTTP server, so use
// the same ws upgrade process described here:
// https://www.npmjs.com/package/ws#multiple-servers-sharing-a-single-https-server
const server = app.listen(3000);
server.on('upgrade', (request, socket, head) => {
wsServer.handleUpgrade(request, socket, head, socket => {
wsServer.emit('connection', socket, request);
});
});
In answer to "How to Send and/or Stream array data that is being continually updated to a client" as arrived at in comment.
A possible solution using WebSockets may be to
Create an interface on the server for array updates (if you haven't already) that isolates the array object from arbitrary outside modification and supports a callback when updates are made.
Determine the latency allowed for multiple updates to occur without being pushed. The latency should allow reasonable time for previous network traffic to complete without overloading bandwidth unnecessarily.
When an array update occurs, start a timer if not already running for the latency period .
On timer expiry JSON.stringify the array (to take a snapshot), clear the timer running status, and message the client with the JSON text.
A slightly more complicated method to avoid delaying all push operations would be to immediately push single updates unless they occur within a guard period after the most recent push operation. A timer could then push modifications made during the guard period at the end of the guard period.
Broadcasting
The WebSockets API does not directly support broadcasting the same data to multiple clients. Refer to Server Broadcast in ws documentation for an example of sending data to all connected clients using a forEach loop.
Client side listener
In the client-side message listener
document.getElementById("keywordsList").innerHTML = e.data;
would be better as
document.getElementById("keywordsList").textContent = keywordList;
to both present keywords after decoding from JSON and prevent them ever being treated as HTML.
So I finally figured out what I wanted to accomplish. It sounds straight forward after I learned enough and thought about how to structure the back end of my project.
If you have two websockets running and one needs information from the other, you cannot run them side by side. You need to have one encapsulate the other and then call the websocket INSIDE of the other websocket. This can easily cause problems down the road for other projects since now you have one websocket that won't fire until the other is run but for my project it makes perfect sense since it is locally run and needs all the parts working 100 percent in order to be effective. It took me a long time to understand how to structure the code as such.

How can I send data to a specific socket?

My problem is that the current solution I have for sending a specific socket using the library "ws" with node.js is not good enough.
The reason is because if I connect with multiple tabs to the websocket server with the same userid which is defined on the client-side, it will only refer to the latest connection with the userid specified.
This is my code:
// Server libraries and configuration
var server = require("ws").Server;
var s = new server({ port: 5001});
// An array which I keep all websockets clients
var search = {};
s.on("connection", function(ws, req) {
ws.on("message", function(message){
// Here the server process the user information given from the client
message = JSON.parse(message);
if(message.type == "userinfo"){
ws.personName = message.data;
ws.id = message.id;
// Defining variable pointing to the unique socket
search[ws.id] = ws;
return;
}
})
})
As you can see, each time a socket with same id connects, it will refer to the latest one.
Example If you did not understand:
Client connect to server with ID: 1337
search[1337] defined as --> websocket 1
A new connection with same ID: 1337
search[1337] becomes instead a variable refering to websocket 2 instead
Websockets provide a means to create a low-latency network "socket" between a browser and a server.
Note that the client here is the browser, not a tab on a browser.
If you need to manage multiple user sessions between the browser and server, you'll need to write code to do it yourself.

UDP multi broadcast nodejs

I'm trying to create a UDP multi broadcast based chat program, the idea being that anyone on the local network can just pop on and start typing and sending messages.
I figure that every client needs two sockets, one to send messages and one to receive messages.
At its simplest, this is what I have now:
"using strict";
const multicast_addr = "224.1.1.1",
bin_addr = "0.0.0.0",
port = 6811;
var udp = require("dgram");
var listener = udp.createSocket("udp4"),
sender = udp.createSocket("udp4");
listener.bind(port, multicast_addr, function(){
listener.addMembership(multicast_addr);
listener.setBroadcast(true);
});
listener.on("message", function (b, other) {
console.log(b.toString().trim());
});
process.stdin.on("data", function (data){
sender.send(data, 0, data.length, port, multicast_addr);
});
(Never mind the echo, that's application logic that will be built on top)
This will echo the message back to the person running the code, but I also ran this at the same time on a linux VM on the same machine, OS X, but didn't see the messages being passed at all.
I'm not sure if that means that
1) My code is incorrect
2) VMs have the same networking as their host machine?
3) Code is correct but my home router is blocking multi broadcast packets?
Ah, I found this neat trick of reusing ports for addresses.
"using strict";
const multicast_addr = "224.1.1.1",
bin_addr = "0.0.0.0",
port = 6811;
var udp = require("dgram");
var listener = udp.createSocket({type:"udp4", reuseAddr:true}),
sender = udp.createSocket({type:"udp4", reuseAddr:true});
listener.bind(port, multicast_addr, function(){
listener.addMembership(multicast_addr);
listener.setBroadcast(true);
});
listener.on("message", function (b, other) {
console.log(b.toString().trim());
});
process.stdin.on("data", function (data){
sender.send(data, 0, data.length, port, multicast_addr);
});
Worked for having OS X talk to Non-VM Ubuntu over local network.

Spawning a Shared Worker in a Dedicated Worker

I'm playing around with WebWorkers. Somehow I had the idea to let the different instances of a page know when another one is closed. Therefore I wrote a Shared Worker and it works fine.
But now I want a Dedicated Worker to act as an interface to the Shared Worker. So that expensive actions in the UI won't affect the continous communication with the Shared Worker.
But I get the error, SharedWorker was not defined. An idea would be to use MessageChannel, but I want it to run at least in Firefox and Chrome and as far I know, Firefox still doesn't have a working implementation of MessageChannel.
So - are there any workarounds for this problem?
You can't create a shared worker object in the dedicated worker. However, you can create a shared worker in the main UI thread and pass its port to the dedicated worker, so they can communicate directly.
As an example, in main thread create both workers, and transfer the port object of the shared to the dedicated:
var sharedWorker = new SharedWorker("worker-shared.js");
sharedWorker.port.start();
var dedicatedWorker = new Worker("worker-dedicated.js");
dedicatedWorker.postMessage({sharedWorkerPort: sharedWorker.port}, [sharedWorker.port]);
In the shared worker you can post messages on this port:
self.onconnect = function(e) {
var port = e.ports[0];
self.setInterval(function() {
port.postMessage('sent from shared worker');
}, 1000);
};
And in the dedicated you can react to them
self.onmessage = function(e) {
var sharedWorkerPort = e.data.sharedWorkerPort;
sharedWorkerPort.onmessage = function(e) {
console.log('received in dedicated worker', e.data);
};
};
You can see this working at http://plnkr.co/edit/ljWnL7iMiCMtL92lPIAm?p=preview

How to create data channel in WebRTC peer connection?

I'm trying to learn how to create an RTCPeerConnection so that I can use the DataChannel API. Here's what I have tried from what I understood:
var client = new mozRTCPeerConnection;
var server = new mozRTCPeerConnection;
client.createOffer(function (description) {
client.setLocalDescription(description);
server.setRemoteDescription(description);
server.createAnswer(function (description) {
server.setLocalDescription(description);
client.setRemoteDescription(description);
var clientChannel = client.createDataChannel("chat");
var serverChannel = server.createDataChannel("chat");
clientChannel.onmessage = serverChannel.onmessage = onmessage;
clientChannel.send("Hello Server!");
serverChannel.send("Hello Client!");
function onmessage(event) {
alert(event.data);
}
});
});
I'm not sure what's going wrong, but I'm assuming that the connection is never established because no messages are being displayed.
Where do I learn more about this? I've already read the Getting Started with WebRTC - HTML5 Rocks tutorial.
I finally got it to work after sifting through a lot of articles: http://jsfiddle.net/LcQzV/
First we create the peer connections:
var media = {};
media.fake = media.audio = true;
var client = new mozRTCPeerConnection;
var server = new mozRTCPeerConnection;
When the client connects to the server it must open a data channel:
client.onconnection = function () {
var channel = client.createDataChannel("chat", {});
channel.onmessage = function (event) {
alert("Server: " + event.data);
};
channel.onopen = function () {
channel.send("Hello Server!");
};
};
When the client creates a data channel the server may respond:
server.ondatachannel = function (channel) {
channel.onmessage = function (event) {
alert("Client: " + event.data);
};
channel.onopen = function () {
channel.send("Hello Client!");
};
};
We need to add a fake audio stream to the client and the server to establish a connection:
navigator.mozGetUserMedia(media, callback, errback);
function callback(fakeAudio) {
server.addStream(fakeAudio);
client.addStream(fakeAudio);
client.createOffer(offer);
}
function errback(error) {
alert(error);
}
The client creates an offer:
function offer(description) {
client.setLocalDescription(description, function () {
server.setRemoteDescription(description, function () {
server.createAnswer(answer);
});
});
}
The server accepts the offer and establishes a connection:
function answer(description) {
server.setLocalDescription(description, function () {
client.setRemoteDescription(description, function () {
var port1 = Date.now();
var port2 = port1 + 1;
client.connectDataConnection(port1, port2);
server.connectDataConnection(port2, port1);
});
});
}
Phew. That took a while to understand.
I've posted a gist that shows setting up a data connection, compatible with both Chrome and Firefox.
The main difference is that where in FF you have to wait until the connection is set up, in Chrome it's just the opposite: it seems you need to create the data connection before any offers are sent back/forth:
var pc1 = new RTCPeerConnection(cfg, con);
if (!pc1.connectDataConnection) setupDC1(); // Chrome...Firefox defers per other answer
The other difference is that Chrome passes an event object to .ondatachannel whereas FF passes just a raw channel:
pc2.ondatachannel = function (e) {
var datachannel = e.channel || e;
Note that you currently need Chrome Nightly started with --enable-data-channels for it to work as well.
Here is a sequence of events I have working today (Feb 2014) in Chrome. This is for a simplified case where peer 1 will stream video to peer 2.
Set up some way for the peers to exchange messages. (The variance in how people accomplish this is what makes different WebRTC code samples so incommensurable, sadly. But mentally, and in your code organization, try to separate this logic out from the rest.)
On each side, set up message handlers for the important signalling messages. You can set them up and leave them up. There are 3 core messages to handle & send:
an ice candidate sent from the other side ==> call addIceCandidate with it
an offer message ==> SetRemoteDescription with it, then make an answer & send it
an answer message ===> SetRemoteDescription with it
On each side, create a new peerconnection object and attach event handlers to it for important events: onicecandidate, onremovestream, onaddstream, etc.
ice candidate ===> send it to other side
stream added ===> attach it to a video element so you can see it
When both peers are present and all the handlers are in place, peer 1 gets a trigger message of some kind to start video capture (using the getUserMedia call)
Once getUserMedia succeeds, we have a stream. Call addStream on the peer 1's peer connection object.
Then -- and only then -- peer 1 makes an offer
Due to the handlers we set up in step 2, peer 2 gets this and sends an answer
Concurrently with this (and somewhat obscurely), the peer connection object starts producing ice candidates. They get sent back and forth between the two peers and handled (steps 2 & 3 above)
Streaming starts by itself, opaquely, as a result of 2 conditions:
offer/answer exchange
ice candidates received, exchanged, and added
I haven't found a way to add video after step 9. When I want to change something, I go back to step 3.

Categories

Resources