A beginner’s guide to Web sockets (SOCKET.IO)

Jerin George
Webtips
Published in
6 min readJul 8, 2020

This article will provide all you rookie developers out there a step by step approach in setting up a real-time chat application with Socket.io.

What are web sockets?

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. Putting it in simpler terms a socket is just a bi-directional channel that facilitates data transfers between a client(browser) and a server.

Sockets vs Http

Sockets are always open i.e the socket API has listeners and once the socket is initialized and open they are continuously “listening” for broadcasted messages. The messages sent by the client can also trigger a server function and can cause a back and forth communication between each other.

Traditional HTTP requests connections open only when the request is sent to the client the connection is open till the response is received and then it closes. So real-time applications like a chat app would need to open and close hundreds of connections in one chat session. Now you get it why HTTP becomes such a tedious approach for real-time communication.

Building a chat application

Photo by Austin Distel on Unsplash

So now the theory is out of the way lets get our hands dirty by building an application using web sockets. We will be using Socket.io which is a popular open-source library for web sockets, ExpressJs, and Nodejs for backend development and Reactjs for frontend development.

  1. Setting up a simple backend server

Start by making a directory and naming it “backend chat” (this is just for the sake of the article you can name it whatever you like) and go ahead and type the command npm init from the terminal once you are in the directory.

Just hit ‘Enter’ to all the parameters asked, you should get a package.json file in your directory this is where all your application dependencies would be listed.

Now we need to install all packages for setting up our server we will install the cors package, nodemon for always monitoring the server, express, and finally the socket.io server package. Go ahead and type the command npm install cors nodemon express socket.io. This should install all the packages and also give you a node modules directory.

Go ahead and create an index.js file this is our entry point to the application.

add the dev command like shown above so that nodemon can run your server. Change the scripts tag in the package.json file.

Now you can run the server with the help of nodemon hit npm run dev on the terminal which would run the “dev” script which we just wrote.

Now to set up a simple running server. Copy the following code in your index.js file.

In the index.js file

Now start the server by running the “dev” script which we had previously written.

Voila! You should now see your server running at port 5000. You can check your browser to see what your server is displaying.

2) Setting up a socket connection

Now, let's import the socket-io library we had installed and initialize a socket instance. A socket instance basically helps us use all the functions in the socket-io package. Import it at the top where we had imported the other modules.

After that, we initialize an io instance this allows us to use functions like io.on, io.emit, etc. More information on io functions can be found here.

You add the following code to your index.js file.

Now we have set up a standard socket connection at the server. The io.on listener is always listening to clients or browsers looking to connect. The socket object returned notifies us of a connection made by a client. Here the socket object will be triggered when a user disconnects or leaves and will run the call back functions. You can add your own events form the client-side which can trigger methods on the server-side.

3) Setting up a client application.

We can use the React framework for the client-side application. This article would only be demonstrating how sockets are set up both on client and server all additional code for building the frontend will be provided on my GitHub at the end of the article.

We are gonna go ahead and type npx create-react-app chatfrontend in our command terminal which is gonna create a react project.

We will go ahead and install the client library from socket-io.

npm install socket.io-client.

Once that is done we are going to create a single component called Chat.js and import it into our App.js file.

App.js

Now we gonna set up the socket connection for the client. We need to set up the endpoint where our backend server is running which is at port 5000.

I have used the useEffect hook which would set up the socket connection before the component loads a class-based equivalent to that would be the componentDidMount function.

Chat.js

Now when we reload the browser we are going to see how our client is connected to the server with the socket connection. The server-side functions get triggered each time a new client is connected. You can check it out in your terminal where your server is running. Every time the browser reloads the client disconnects from the socket connection and reconnects.

4) Setting up event emitters

The socket object we get is what is used to communicate between the server and the client. We can use the built-in method called emit which is going to send particular data from client to server.

Let's emit one message from the client to the server with the emit function. We are going to trigger the emit function in the useEffect function. We are sending an object named “message” which has a string.

Chat.js

Now we can set up a listener named “test” same as the emitter, at the server-side in index.js file and display the message we get from the client on the terminal.

index.js(server)

We have two listeners currently one which is listening to the ‘disconnected’ event and one custom listener which we made called ‘test’. We deconstruct the message object and display it on the terminal.

terminal running the server

We get the data we had sent from the client to the server. We can add rooms or different custom emitters to trigger different functions and events. Thus the SocketIO library allows developers a lot of flexibility to use WebSockets in their application.

Conclusion

This article is meant to get all the new developers to get started with sockets and real-time application development without getting overwhelmed by the documentation. This article just scratches the surface of Web sockets and there plenty of interesting things that can be developed with this library. Github link to my chat application is listed below feel free to check it out.

--

--