Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Real-Time Applications with WebSocket

Real-Time Applications with WebSocket

WebSocket is a communication protocol that enables real-time, full-duplex communication between a client (usually a web browser) and a server. It allows for continuous data exchange, making it ideal for building real-time applications such as chat apps, online games, collaborative tools, and more. Below are steps to create a simple real-time chat application using WebSocket with Node.js:

Step 1: Set Up Your Project

Create a new directory for your project and navigate into it:

mkdir websocket-chat
cd websocket-chat
 

 Initialize the project and create a package.json file:

npm init -y
 

Install the ws (WebSocket) library:

npm install ws
 

Step 2: Create the Server

Create a server.js file and set up the WebSocket server:

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });

server.on('connection', (socket) => {
  console.log('New connection established');

  // Handle incoming messages
  socket.on('message', (message) => {
    // Broadcast the message to all connected clients
    server.clients.forEach((client) => {
      if (client !== socket && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  // Handle disconnection
  socket.on('close', () => {
    console.log('Connection closed');
  });
});
 

Step 3: Create the Client (HTML & JavaScript)

Create an index.html file and add the following content:

 
 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Chat</title>
</head>
<body>
  <div id="messages"></div>
  <input type="text" id="messageInput" placeholder="Type a message...">
  <button onclick="sendMessage()">Send</button>

  <script>
    const socket = new WebSocket('ws://localhost:3000');

    socket.addEventListener('open', (event) => {
      console.log('Connected to server');
    });

    socket.addEventListener('message', (event) => {
      const messages = document.getElementById('messages');
      messages.innerHTML += `<p>${event.data}</p>`;
    });

    function sendMessage() {
      const messageInput = document.getElementById('messageInput');
      const message = messageInput.value;
      socket.send(message);
      messageInput.value = '';
    }
  </script>
</body>
</html>
       

 

Step 4: Start the Server

In your terminal, run the server:

node server.js
 

Step 5: Open the Client in a Web Browser

Open index.html in a web browser. You can now send messages in the chat input field, and they will be broadcasted to all connected clients.