Building Real-time Applications with WebSockets and Socket.io

WebSockets are a protocol that allows for real-time, two-way communication between a client and a server. Socket.io is a JavaScript library that simplifies building real-time applications with WebSockets. In this tutorial, we’ll explore how to build a real-time chat application with WebSockets and Socket.io.

Prerequisites

Before we begin, make sure you have the following installed on your machine:

  • Node.js (version 6 or higher)
  • npm (version 3 or higher)

Setting up the project

First, let’s create a new directory for our project and initialize it as a Node.js project:

mkdir real-time-chat
cd real-time-chat
npm init -y

Next, let’s install the necessary dependencies:

npm install express socket.io

Building the server

Let’s start by building the server. Create a new file called server.js in the root of the project and add the following code:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.Server(app);
const io = socketIO(server);

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(PORT, () => {
  console.log(`listening on *:${PORT}`);
});

This code creates an Express app, sets up a server with the http module, and initializes Socket.IO on the server. The app responds to requests on the root URL by serving up an index.html file, and Socket.IO listens for new connections and disconnect events.

Building the client

Now let’s create the front-end of our chat application. Create a file called index.html in the root of the project and add the following code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Real-time Chat</title>
</head>
<body>
  <ul id="messages"></ul>
  <form action="">
    <input id="message-input" autocomplete="off" />
    <button>Send</button>
  </form>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();

    const messageList = document.querySelector('#messages');
    const messageInput = document.querySelector('#message-input');
    const form = document.querySelector('form');

    form.addEventListener('submit', (e) => {
      e.preventDefault();
      const message = messageInput.value.trim();
      if (message) {
        socket.emit('chat message', message);
        messageInput.value = '';
      }
    });

    socket.on('chat message', (message) => {
      const li = document.createElement('li');
      li.innerText = message;
      messageList.appendChild(li);
    });
  </script>
</body>
</html>

This code sets up the HTML structure of the chat application, including a form for sending messages and a list for displaying them. It also includes a script tag that loads the Socket.IO client library and sets up the necessary event listeners for sending and receiving messages.

Testing the application

Now that we have our server and client code, let’s test the application. Start the server by running node server.js in the terminal, then navigate to `http://localhost:3000` in your browser.

You should see the chat interface displayed in the browser window. Open multiple browser tabs or windows to simulate multiple users, and try sending messages to see them appear in real time.

Conclusion

In this tutorial, we explored how to build a real-time chat application with WebSockets and Socket.IO. By building a server that listens for new connections and sending messages using the emit() method, and a client that listens for messages and sends them using the on() and emit() methods, we were able to build a real-time chat application with just a few lines of code.

Socket.IO also includes support for rooms, namespaces, and other advanced features that allow for building more complex real-time applications. With Socket.IO and WebSockets, the possibilities for real-time communication on the web are endless.

Related Post