Simple Chat Application using Socket.io


Objectives

Learn how to create a simple real-time chat app using socket.io.

Tech Stack

What is WebSocket?

WebSocket is a realtime technology that enables bidirectional, full-duplex communication between client and server over a persistent, single-socket connection. The WebSocket connection is kept alive for as long as needed (in theory, it can last forever), allowing the server and the client to send data at will, with minimal overhead. To checkout more details, visit here.

How do WebSockets work?

In a nutshell, working with WebSockets involves three main steps:

  • Opening a WebSocket connection: The process of establishing a WebSocket connection is known as the opening handshake, and consists of an HTTP request/response exchange between the client and the server.
  • Data transmission over WebSockets: After a successful WebSocket handshake, the client and server can exchange messages (frames) over the persistent WebSocket connection. WebSocket messages may contain string (plain text) or binary data.
  • Closing a WebSocket connection: Once the persistent WebSocket connection has served its purposes, it can be terminated; both the client and the server can initiate the closing handshake by sending a close message.

Take a look at the figure below, which will help you grasp the concept more easily:

Use Socket.io

What is Socket.io

Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server.

It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.

We'll create a basic chat application to demonstrate how socket.io works and explore it's convenient api.

For the client side, I recommend include the client bundle from a CDN. Checkout the Client Installation here.

For the server side, node and express are required. Checkout the Server Installation here.

Demo

The web framework

Our initial objective is to create a basic HTML webpage that includes a form and a list of messages. To accomplish this, we will utilize the Node.js web framework called Express.

Create a package.json

Install express

npm install express@4

Install typeScript

npm install typescript --save-dev  

Create a index.ts file

The app.get() method is used to define a route for the root URL ("/") and specifies a callback function that handles the request and response objects (req and res). Inside the callback function, the server responds with the HTML string "Hello world" using the res.send() method.

Execute the code

ts-node index.ts

You should see something similar on your browser:

Serving HTML

We don't want to serve all HTMLs in a single file. We can decouple it to an index.html file.

Create index.html

As this is a demo app, I will include the styling directly within the HTML file for simplicity.

This is a straightforward webpage that features an input text field and a submit button.

Integrating Socket.IO

Socket.IO is composed of two parts, I've mentioned it earlier.
  • A server that integrates with (or mounts on) the Node.JS HTTP Server socket.io
  • A client library that loads on the browser side socket.io-client

Install the module

npm install socket.io

For the server side, we modify index.ts

  • io.on("connection", ...) listens for a "connection" event, which occurs when a client establishes a WebSocket connection with the server.
  • socket.on("chat message", ...) listens for a "chat message" event sent by a client.
  • io.emit("chat message", msg) broadcasts the "chat message" event and its payload (msg) to all connected sockets, including the socket that sent the message.

For the client side, we modify index.html

I load the socket.io-client in the script tag using CDN. And then I add simple Javascript code so that when the user types in a message, the server gets it as a chat message event. And on the client side when we capture a chat message event we’ll include it in the page.

Execute index.ts and you can see your application running on port 3000. And that's a wrap! I hope you enjoy it!

Conclusion

In conclusion, Socket.io emerges as a game-changer in enabling instant, bidirectional communication between servers and clients. By eliminating the need for manual page refreshing, it empowers real-time updates, enhancing user experiences and improving the performance of web applications.

Source