Getting Started with WebSockets
In An Introduction to WebSockets With Nodejs, I went over the idea behind the WebSocket protocol and how it differed from the more common HTTP protocol. The WebSocket protocol enables persistent connections between the server and the client, with each connection known as a websocket. Such a connection allows the server to send data to the client without receiving a request from the client. In contrast, the connections made between a client and server in the HTTP protocol are terminated at the end of the process, or server response. If the server needed to send data to the client, it could not and would need the client to make a specific request for that data. And for a server to initiate communication with the client, the server must be configured in a specific way. Luckily this configuration is handled by a library called Socket.io, which enables bidirectional communication between the client and the server. Let’s take a look at how to implement websockets with Socket.io.
To get started we will need to install the socket.io package and require it into the Node project.
npm install --save socket.io
Next, we will require it and also reconfigure the server setup.
// index.jsconst http = require('http');
const express = require('express');
const socketio = require('socket.io');const app = express();
const server = http.createServer(app);
const io = socketio(server);const port = process.env.PORT || 3000;server.listen(port, () => console.log(`Server is listening on port ${port}`));
First, we are loading the “http” core Node module to create a server using its “createServer” method. Creating a server is this way is ordinarily bypassed with the “express” library which handles it instead of explicitly carrying out that step. And since the socket.io library requires access to the server to enable the WebSocket protocol, the server is established explicitly and provided to the function that is loaded in via the “socket.io” module.
Now that the server is configured to allow for persistent connections between client and server, we can define events to listen for to produce on output by the server. One of the events that the server will listen and respond to is the “connection” event which is when a client connects to the server, creating a websocket connection.
// index.jsconst http = require('http');
const express = require('express');
const socketio = require('socket.io');const app = express();
const server = http.createServer(app);
const io = socketio(server);const port = process.env.PORT || 3000;io.on('connection', () => {
console.log('New websocket connection!');
});server.listen(port, () => console.log(`Server is listening on port ${port}`));
Added to the configuration code before is the new line which accesses the server stored in the “io” variable. The server “on” a new “connection” or client visiting the root path served on port 3000 will trigger the server to respond by logging to the console. But in order for the client to connect to this specially configured server requires its own configuration from the Socket.io library. This is carried out by loading in a script on the root index.html file that is served which will allow the client-side to connect to the server. In the case of a React application, the following can be added inside the “body” tag of the index.html file.
<body>
<script src="/socket.io/socket.io.js"></script>
<div id="root"></div>
</body>
By adding this script, the entire React application will be able to establish a websocket connection with the server. The final step in ensuring that the client-side establishes websocket connection is invoking “io()” which is provided by the script that was loaded into the HTML. This function can be invoked in the “index.js” file which will initialize the client-side for websocket connections with the server and will trigger the server to log to the console that a new connection was made, as shown in the code above.
Having followed these steps, you should now have configured your application to behave using the WebSocket protocol and can take advantage of real-time data communication. To read more about the Socket.io library and the initial configuration, you can check out their documents.