Search code examples
websocketsocket.ioweb-worker

socket.io Websocket connection inside a HTML5 SharedWorker


I hope you all are doing well. I'm trying to establish connection to socket.io server from inside of the worker.js file using importScripts which loads the socket.io-client js file which is in the same directory with worker.js. After loading socket.io-client by using var socket = io.connect('http://38.98.xxx.xxx:6000'); I am trying to establish connection to socket.io server on different host, but it ain't working. Please point me in the right direction.I appreciate any help.

    <script>
    var worker = new SharedWorker("http://baseUrl.com/js/push/worker/worker.js");

    worker.port.addEventListener("message", function(e) {
        console.log("Got message: " + e.data);
    }, false);
    worker.port.start();
    worker.port.postMessage("start");

</script>

worker.js

importScripts('socket.io.js');

var socket = io.connect('http://38.98.154.167:6000');

var connections = 0;

self.addEventListener("connect", function(e) {
    var port = e.ports[0];
    connections ++;
    port.addEventListener("message", function(e) {
        if (e.data === "start") {

            port.postMessage('hello');
        }
    }, false);
    port.start();
}, false);


socket.on('connect', function () {
    port.postMessage('connect');
});

socket.on('disconnect', function () {
    port.postMessage('disconnect');
});

Solution

  • I figured it out. Just had to move

    socket.on('connect', function () {
        port.postMessage('connect');
    });
    
    socket.on('disconnect', function () {
        port.postMessage('disconnect');
    });
    

    into the self.addEventListener("connect", function(e) {});in the worker.js and change from var socket=io.connect('http://38.98.xxx.xxx:6000'); to

    var socket = io('http://38.98.xxx.xxx:6000');
    

    Here is the working example is case if anybody needs.

    worker.js

      importScripts('socket.io.js');
    
    var socket = io('http://38.98.xxx.xxx:6000');
    
    var connections = 0;
    
    self.addEventListener("connect", function(e) {
        var port = e.ports[0];
        connections ++;
        port.addEventListener("message", function(e) {
            if (e.data === "start") {
    
                port.postMessage('hello');
            }
        }, false);
        port.start();
    
        socket.on('push', function(pushed){
    
            port.postMessage(pushed);
        });
    
    
        socket.on('connect', function () {
            port.postMessage('connect');
        });
    
        socket.on('disconnect', function () {
            port.postMessage('disconnect');
        });
    
    }, false);