DEV Community

Christopher Booth
Christopher Booth

Posted on • Updated on

Introduction to socket.IO

Socket IO Logo

What is it?

It's a tad confusing what socket IO is.
It's a JavaScript library that allows for real-time, bidirectional, and event-based communication between the client browser and the server. So what does that look like or even mean? Let's take a look using visual aids.

Traditional HTTP client server talk

In the above photo we can see the client makes a request to the server. The server then processes the request and sends back some data. This is standard for any HTTP request. The connection opens, the request is sent, the request is processed, the data is returned, and finally the connection closes. This is a one time trip not to be repeated unless the page reloads or the request is on a timer or some other manual process. Furthermore, the server cannot decide to send data to the client on its own. It must await a request.

Socket client server talk

Conversely, connections from Socket IO are kept alive. They keep the connection between client and server open until told otherwise. This allows for updates from the server to be sent to the client unprompted and allows for near instantaneous communication between server and any number of clients.

With socket IO data can move more freely from server to client(s).

Here's a scenario:

Client A and Client B both open a socket connection to the same node server running socket io. Data can now flow freely from server to their clients.

Client A sends a message to the node server

The server listens for the message event and receives the message from client A.

The server decides to send the message to connected Client B so that it may see the message from A.

In the above scenario client B did absolutely nothing to request the message from the server. All it did was open the connection and wait for an event to be fired its way.

Adding Socket IO to your Node Server

This assumes you are familiar with setting up a basic express server using Node.

To begin using socket IO we must install it first:
npm install socket.io --save

Inside your server js file we need to add socket IO.
The most basic implementation should look like this:

//require express
const express = require('express');
//require socket.io
const socket = require('socket.io');

const app = express();

//start server
const server = app.listen(3000, () => {
    console.log('Server listening on port 3000');
});
//attach socket io to server
const io = socket(server);

io.on('connect', (socket) => {
    console.log(`Client connected with socket ID: ${socket.id}`);
});
Enter fullscreen mode Exit fullscreen mode

The above adds socket io to the server and sets up an event listener for incoming connections. At the moment it simply logs their socket Ids to the console.

Adding Socket IO to React Client

The client needs its own socket client. I've chosen to use a hook based client.
npm i use-socket.io-client

In a react component we must make our connection to the server.

import React from 'react'
import useSocket from 'use-socket.io-client';

function example() {
    const [socket] = useSocket();
    socket.connect();

    return (
        <div>
            Hello World
        </div>
    )
}

export default example
Enter fullscreen mode Exit fullscreen mode

Congratulations you've successfully connected the client to the server at this point. One thing to note is within useSocket()
When it is invoked you may pass in the address of the server it is meant to connect to.
const [socket] = useSocket('ws://someAddress')

This is not needed, however, if socket io is meant to connect to the same server the react app is accessed from. It will handle that connection on its own.

If you want to see more examples of what you can do with socket IO take a look at the official docs. Particularly take a look at their emit cheatsheet

Top comments (0)