Socket.IO is a library that makes us possible to implement a 2-way communication channel between client and server with low latency based on events. We can use Socket.IO to implement a WebSocket server. Originally Socket.IO was written in JavaScript but some other languages are also supported like Java and Python. In this tutorial, I will discuss with you more about Socket.IO, how to implement a WebSocket server using Socket.IO and how to connect and send messages to the Websocket server!
Socket Server
First, I will create a new NodeJS project to implement a WebSocket server as an example:
Next, we will add the socket.io dependency to the project:
1 |
npm install socket.io -save |
Now, I will add the index.js file to start working with the NodeJS project:
We will initialize Socket.IO’s Socket Server object from NodeJS’s HTTP module as follows:
1 2 3 4 5 6 7 8 9 10 |
const { Server } = require("socket.io"); const httpServer = require("http").createServer(); const io = new Server(httpServer); io.on('connection', (socket) => { console.log('Connected to client!') }); httpServer.listen(8080, () => console.log('Server running on port 8080')); |
In the above example, I just initialized the Socket Server object from the HTTP Server object with default configurations. You can use another constructor with a server option parameter.
1 2 3 |
const io = new Server(httpServer, { }); |
You can refer to the server options that Socket.IO supports here.
Once we have the Socket Server object, we can use the on() method of this object to add code to handle events from the client to the server.
There are 3 default events supported by Socket.IO Server: connection, connect, and new_namespace. Event connection and connect are the same!
The event connection is called when there is a connection from the client to the server and as you can see in the example above, I have code to print the words “Connected to client!”.
To start this server, add the following line to your project’s package.json file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "name": "socketio-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "socket.io": "^4.4.1" } } |
The output when running npm start will be as follows:
Now, I will create a client application to connect to the Websocket server that we just started.
Socket Client
The NodeJS project is as follows:
I also created a new file index.js and added socket.io-client dependency as follows:
1 |
npm install socket.io-client -save |
Result:
We will create a new Socket Client object that connects to the Socket Server using the io() method as follows:
1 2 3 4 5 6 7 8 9 |
const { io } = require("socket.io-client"); const socket = io("http://localhost:8080", { autoConnect: false }); socket.onAny((event, ...args) => { console.log(event, args); }); socket.connect(); |
Here, any event that is emitted from the Socket server, we will print to the console of that client application!
The default events that Socket.IO supports for Socket Client are connect, disconnect, and connect_error.
Similar to when starting the server, we also add the following line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "name": "socketio-client-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "socket.io-client": "^4.4.1" } } |
into the package.json file of the socketio-client-example project to start the client application.
At this point, you will see the following output in the console log of the Socket server when starting the client application:
Send a message
If you modify the Socket Server code so that every time a client connects, the Socket Server will send a message to this client:
1 2 3 4 5 6 7 8 9 10 11 12 |
const { Server } = require("socket.io"); const httpServer = require("http").createServer(); const io = new Server(httpServer); io.on("connection", (socket) => { console.log("Connected to client!"); socket.emit("welcome", "Hello"); }); httpServer.listen(8080, () => console.log("Server running on port 8080")); |
then when starting the client application, you will see an event sent from the server as follows:
As you can see, we use the emit() method of the Socket object with 2 parameters, event name, and data to send a message from the Socket Server to the client.
You can also send messages from the client to the Socket Server as follows:
1 2 3 4 5 6 7 8 9 10 11 |
const { io } = require("socket.io-client"); const socket = io("http://localhost:8080", { autoConnect: false }); socket.onAny((event, ...args) => { console.log(event, args); }); socket.emit("welcome", "Hello from client"); socket.connect(); |
On the Socket Server side, we also need to add code to handle this “welcome” event, for example as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const { Server } = require("socket.io"); const httpServer = require("http").createServer(); const io = new Server(httpServer); io.on("connection", (socket) => { console.log("Connected to client!"); socket.emit("welcome", "Hello"); socket.on("welcome", (data) => { console.log(data); }); }); httpServer.listen(8080, () => console.log("Server running on port 8080")); |
Run both the Socket Server and the client again, you will see that the Socket Server receives a message from the client as follows: