H. Pauwelyn H. Pauwelyn - 7 months ago 51
Node.js Question

Let socket and http server listen to same port

I make a website and it must have real-time communication to the server. With real-time I mean if a user vote on a topic, all connected clients must see the new average of the votes.

I've try something but I've got this question: How can I create a socket server and a HTTP server that listen to the same port with Node.JS? It I run code below, I've got this exception:

Error: listen

Here is my server code:

let port = 8080;

const httpServer = require('http'),
app = require('express')(),
socketServer = http.Server(app),
io = require('socket.io')(httpServer);

httpServer.createServer(function (req, res) {
console.log('http server created on 8080');

socketServer.listen(port, function(){
console.log('listening on 8080');

Thanks in advance


It looks like you want something similar to this:

const port = 8080;

let app    = require('express')();
let server = app.listen(port);
let io     = require('socket.io')(server);

This attaches an Express app and a socket.io server to the same HTTP server (which is returned by app.listen()). That's how you run both the app and the socket.io server on the same port.