Socket.IO – How to implement Socket.IO in Node.js – Part 2
In this article, we’ll show you how to implement Socket.IO in Node.js. As we already discussed about the implementation flow of the Socket.IO application in the first part of the article so now it’s time to move on to the second part of the article to implement socket in Node.js application (Backend).
Socket.IO – How to implement Socket in Node js, Node.js tutorial with socket.io, real-time chat application using nodejs, Building a Node.js WebSocket Chat App with Socket.io and react, Getting Started with Socket.IO, Node.js and Express, socket with node js example, How to use socket.io in angular with node.js?, Node socket.io example, web-socket in NodeJS, full socket.io client and server example.
Checkout more articles on Node.js/JavaScript
We planned to divide this article into three parts.
- Part 1 – Implementation flow
- Part 2 – Implement Socket.IO in Node.js (You are here…)
- Part 3 – Implement Socket.IO in React
Way to implement Socket.IO in Node.js
- Setup server using express
- Install dependency of socket
- Attach socket to the node server
- Create an event for client subscription
- Emit the message after subscription
1. Setup server using express
To begin the implementation, We have to start with simple REST API integration in Node.js using express framework. If you don’t know about it then refer to the link where you can find how to create REST API.
To enable the CORS we’re going to install cors npm package. Run the code below to install it.
1 | npm i cors |
After updating the CORS in the node server, your server.js
file should look like this.
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var express = require('express'), app = express(), port = process.env.PORT || 4000; const cors = require('cors'); app.use(cors({ credentials: true, origin: 'http://localhost:3000' // URL of the react (Frontend) app })); app.get('/', (req, res) => { res.send('Welcome to Socket.IO App! - Clue Mediator'); }); app.listen(port, () => { console.log('Server started on: ' + port); }); |
2. Install dependency of socket
To implement socket in Node.js, we have to install socket.io npm package. It will help us to connect the react application. Run the following command to install the dependency.
1 | npm install socket.io |
3. Attach socket to the node server
Now, let’s attach the Socket.IO to the Node.js HTTP server listening on port 4000
. So let’s create a socket.js
file at root level where we will manage the code of the socket connection and events.
socket.js
1 2 3 4 5 6 7 | const socket = io => { io.on('connection', client => { console.log('New Connection'); }); } module.exports = socket; |
Also we have to slightly update the server.js
file. Check the following code of the server file.
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var express = require('express'), app = express(), port = process.env.PORT || 4000; const cors = require('cors'); app.use(cors({ credentials: true, origin: 'http://localhost:3000' // URL of the react (Frontend) app })); app.get('/', (req, res) => { res.send('Welcome to Socket.IO App! - Clue Mediator'); }); var server = app.listen(port, () => { console.log('Server started on: ' + port); }); // attach socket to the node server var io = require('socket.io').listen(server); require('./socket')(io); |
4. Create an event for client subscription
Let’s create an event to the socket for client subscription. So once a client connects to the socket then we will ask for subscription to listen to the message.
1 2 3 4 | // socket event for client subscription client.on('subscribeToDateEvent', interval => { console.log('Client is subscribing with interval: ', interval); }); |
Here we’ll get the interval for emitting the message in each interval.
5. Emit the message after subscription
Now at last we have to emit the message as a current UTC date to the client side.
1 2 3 4 | // emit message to the client side setInterval(() => { client.emit('getDate', new Date().toUTCString()); }, interval); |
So let’s combine all code together and see how it looks.
socket.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const socket = io => { io.on('connection', client => { console.log('New Connection'); // socket event for client subscription client.on('subscribeToDateEvent', interval => { console.log('Client is subscribing with interval: ', interval); // emit message to the client side setInterval(() => { client.emit('getDate', new Date().toUTCString()); }, interval); }); }); } module.exports = socket; |
That’s it for today.
In Part 3 of this article, we’ll implement socket in ReactJS using socket.io-client.
Thanks for reading. Happy Coding!