fanguitocoder
fanguitocoder

Reputation: 13

Node.js Websocket server won't work online

I'm implementing a very simple Node.js Websocket server for a game in HTML5 + PHP. I tested my server locally and works fine, but when I deployed my server and client (in different domains, of course), I just can't connect them. I deployed the server at https://evennode.com. I'm new to Node.js, maybe I'm missing something in my code.

var users = [];
var WebSocketServer = require('ws').Server;

var connections = {};
var registered  = {}; 

var connectionIDCounter = 0;

var port = process.env.PORT || 80;

var wss = new WebSocketServer({port: port}, function(){

    console.log('Listening on port: ' + port);

});

wss.on('connection', function(socket) {

    socket.id = connectionIDCounter ++;

    connections[socket.id] = socket;
    registered[socket.id] = 'Guest' + socket.id;

    connections[socket.id].position = {};
    connections[socket.id].position.x = 0;
    connections[socket.id].position.y = 1.8;
    connections[socket.id].position.z = 0;

    console.log('Connected: ' + socket.id);

    socket.on('message', function(message) {
        var resultObject = JSON.parse(message);

        parseMessage(this.id, resultObject);        
    });

    socket.on('close', function(message) {
        sendUserState(this.id, 'disconnected'); 

        delete registered[this.id];
        delete connections[this.id];    

    });

}); 

I little help would be appreciated.

Upvotes: 0

Views: 1409

Answers (1)

mike
mike

Reputation: 5213

The hosting at www.evennode.com uses Phusion Passenger to run Node.js apps which in turn uses inverse port binding (as mentioned e.g. here by the author) which makes this example not work when hosted by evennode.com.

There's a way though to make it work even with "inverse port binding" in place.
You first need to create an http server and then pass it to the ws constructor.

A simplified example below:

var server = require('http').createServer();
var WebSocketServer = require('ws').Server;

var wss = new WebSocketServer({server: server}, function(){});

server.listen(3000);

wss.on('connection', function(socket) {
  ...
});

Hope this helps solve the issue.
Btw. there's also an example with Socket.io if anyone is interested.

Upvotes: 1

Related Questions