DEV Community

Amit Tiwary
Amit Tiwary

Posted on

Socket.io in Nodejs using Nginx

Socket.IO helps in real-time, bi-directional and event-based communication between the browser and the server. socket.io is available on npm and it can be installed using the command

npm install socket.io
Enter fullscreen mode Exit fullscreen mode

We create a http.server using the http createServer() method.

const http = require('http');
const server = http.createServer();
Enter fullscreen mode Exit fullscreen mode

To start this server we need to use the listen method.

server.listen(port);
Enter fullscreen mode Exit fullscreen mode

Now initialize the socket.io so that we can start listening the emitted events and also can emit the events. We can use the http.listen.createServer().

const io = require('socket.io')(server);
// create a socket conection 
io.sockets.on('connection', function (socket) {
// receive the event 'event name' 
  socket.on('event name', function (name) {
    //do action once socket event received
  });
});
Enter fullscreen mode Exit fullscreen mode

There is no need of https.createServer(), http createServer() will work here.

Let's setup the nginx to support the socket.io. If their is only single instance of Nodejs runnig then it won't required any additional configuration but if their is multiple instance running then we need to make changes so that nginx forward the request from client to same port on which it was registered initially else server will send error session id unknown.

 upstream backend {
    ip_hash; // it is required so that socket.io request forward to the same port on which it was registered
    server ip_address;
}

server {
    server_name www.example.com;

    location / {
       proxy_pass http://backend;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)