DEV Community

Amit Tiwary
Amit Tiwary

Posted on

5 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay