Start Using Socket.io in 4 Minutes

A Quick Tutorial With Sample Code

Malinda Lin
Webtips
4 min readJun 9, 2020

--

Socket.io is a JS library that uses WebSockets protocol to allow bi-directional communication between server and client. It is popular because it offers out-of-the-box features that are not available in WebSockets alone. Also, in case WebSockets is not supported, Socket.io has the option to fall back to long polling to keep your connection active across all clients.

To get started, make sure you npm install socket.io. Also, create three files: the server-side file, the client-side file, and the HTML file being served to the browser. In my examples, I call these files server.js, index.html, and client.js.

These are the steps to use Socket.io:
1. Create a server
2. Initiate socket on server-side
3. Initiate socket on client-side
4. Set up event listeners and emit functions!

Create a server in the server-side file. In my example, I created an Express server but a simple HTTP server works too.

// server.js
const express = require('express');
const app = express();
const clientPath = `${__dirname}`;app.use(express.static(clientPath));app.get('/', (req, res) => {
res.sendFile(`${clientPath}/index.html`);
});
const PORT = process.env.PORT || 5000;// server instance
const server = app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});

Next, add sockets to both the server-side and client-side because together, they act like a communication bridge. To set up a socket on the server: import the socket.io library using the ‘require’ keyword, pass in your server instance, and set up the connection event listener. When the client-side socket is added, the connection event listener allows any client that connects to have access to the connection event listener’s callback function which holds all socket event listeners (I explain socket event listeners later):

// server.js
const socketio = require('socket.io');
// sets up socket
const io = socketio(server);
// connection event listener
io.on('connection', socket => {
/* add your socket listeners here */});

To set up a socket on the client-side: import the ‘socket-client’ library into your HTML file, then import the client-side file. Then, in your client-side file, invoke io to complete the bridge. Now, when a connection is made, the connection event listener in the server file will trigger.

<-- index.html -->
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
____________________________________________________________________
// client.js
const socket = io();
/* add regular event listeners here *//* add sockets event listeners here */

Then, you will need to create socket listeners for both the client and server. Socket event listeners pick up messages that cross the bridge. Use ‘socket.on(‘insert destination name’, callback)’ to create a socket event listener and assign it a name. The callback function is invoked when the socket event listener is triggered. To trigger a socket event listener, we use emit functions like this ‘socket.emit(‘insert destination name’, data, …)’. Emit functions tell your messages where to go, and what to send. In the emit function, make sure you use the name of the socket event listener that you want to trigger. You can pass as many arguments as you want in a single emit function.

// server.js
io.on('connection', socket => {
socket.on('give me a name', (string, int, fn) => {/* io.emit will trigger all connected client sockets.
Remember, clients can also have socket event listeners */
io.emit('client socket name', 'any data types here')
})
});
____________________________________________________________________
// client.js// after the name(string), you can pass any data types
socket.emit('give me a name', 'string', 10, function)
// client socket listener
socket.on('client socket name', (string) => {
/* here is where I would use the data received from one connected
client and display it to this client */

})
Client Mary’s msg goes to Server and Server sends Client Mary’s message to Client John and Client David

Let’s imagine a chat application to solidify what we’ve learned. Mary, John, and David are all using the same chat app. Mary types a message and hits the submit button which triggers an event listener that uses ‘socket.emit’. ‘ socket.emit’ takes Mary’s message and triggers the socket event listener on the server. The server socket event listener will then trigger connected client sockets using ‘io.emit’. From there, connected clients will run DOM manipulation that displays Mary’s message to David, John, and Mary’s screens.

These resources help you use different emit functions:
https://stackoverflow.com/questions/32674391/io-emit-vs-socket-emit
https://socket.io/docs/emit-cheatsheet/

See below for my full code and explanations. Feel free to clone these files from my GitHub Repo and try it out. As always, if you have questions reach out to me on LinkedIn!

--

--