I wanted to build a node.js chat server on heroku, the chat clients are going to be iOS apps.
My first attempt is to build a server based on socket.io. It works, but I don't like the fact the the iOS app is talking to the server using long polling instead of websocket or tcp socket.
So my second attempt is to build the server using real TCP socket, code as below:
var net = require('net');
var sockets = [];
var server = net.createServer(function(socket){
sockets.push(socket);
socket.on('data', function (data) {
for(var i=0; i< sockets.length; i++)
{
sockets[i].write(data);
}
});
socket.on('end', function() {
var i = sockets.indexOf(socket);
sockets.splice(i, 1);
})
});
var port = process.env.PORT || 5000;
console.log("server listening to port " + port);
server.listen(port);
If I deploy this node.js server code in localhost, i can successfully send and receives chat to the TCP server using Terminal as test client
nc localhost 5000
BUT, if I deploy this server code in heroku, I couldn't establish a tcp connection with the server anymore.
My understanding is server will be listening at the process.env.PORT.
So I first traced out this port that the server is listening, e.g. 30134.
Then If I attempt to connect in this way:
nc http://my-heroku-app.herokuapp.com 30134
Nothing happens.
I think I have some fundamental misunderstanding somewhere. Can anyone guide me? Is Real TCP socket chat possible on heroku server?
Heroku does not support websocket. This is why, for example, socket.io needs to be forced to use xhr-polling. (see https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku).
Instead of using sockets directly, you could use something like socket.io which supports multiple transports.
This is because they use and older version of nginx, which did not have full web socket support.
Plus, the port your app is listening on, e.g. 30134 is proxied by nginx from your heroku hostname on port 80 to your app port on heroku's internal network.
I know I'm very late to this party but I wrote an addon to route raw TCP sockets into Heroku ( https://addons.heroku.com/ruppells-sockets ) to support a project I was working on. It's very much beta so be gentle.
If you still need this functionality I'd be keen to get some feedback. The documentation for the addon links to an example nodejs TCP and Websocket chat server for inspiration.