Thursday, 11 May 2017

WebSockets Locally vs Heroku - NodeJS

I have the following code working on my client. I have tried multiple things such as using wss, removing the port from my client as another SO post recommended. I get either a handshake error, a err_connection_refused, or it will eventually time out. Why is that, when this code works perfectly when serving locally? Obviously I replaced ws://localhost:8080 to wss://sitename.herokuapp.com:8080, I also tried using the direct IP address for the heroku app.

CLIENT

    const ws = new WebSocket("ws://localhost:8080");
    ws.onopen = function(e) {
        console.log("WEB SOCKET OPENED");
        ws.send("ready!");
    };
    ws.onclose = function(e) {
        console.log("WEB SOCKET CLOSED");
    };
    ws.onerror = function(e) {
        console.log(e)
    }
    ws.onmessage = function(data) {
    //My long function
    }
    //grab data every 3 seconds
    setInterval(function() {
      ws.send("run again");
      doSomething();
    }, 3000);

SERVER

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 8080 });

wss.on("connection", function(ws) {
    ws.on("message", function(message) {
        wss.clients.forEach(function(client) {
            request(url, function(err, res, bod) {
                var stringedRes = JSON.stringify(bod);
                ws.send(stringedRes);
            });
        });
    });
});



via Austin Truex

No comments:

Post a Comment