Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 EADDRINUSE

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');
}).listen(port);

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

Thanks in advance

like image 911
H. Pauwelyn Avatar asked Nov 16 '16 09:11

H. Pauwelyn


People also ask

Can two server listen on same port?

The short answer is “no, not on the same host."

Can a socket IO and express on same port?

On Scalingo, your application must listen to the port defined in the PORT environment variable dynamically defined by the platform.

What is a socket listener?

Conceptually, a server socket listens on a known port. When an incoming connection arrives, the listening socket creates a new socket (the “child” socket), and establishes the connection on the child socket.

How do I emit to a specific socket?

To send a message to the particular client, we are must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using, socket.broadcast.to('ID'). emit( 'send msg', {somedata : somedata_server} ); For example,user3 want to send a message to user1.


1 Answers

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.

like image 197
robertklep Avatar answered Oct 18 '22 23:10

robertklep