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
The short answer is “no, not on the same host."
On Scalingo, your application must listen to the port defined in the PORT environment variable dynamically defined by the platform.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With