NashTech Insights

WebSockets for Real-Time Communication in JavaScript

Alka Vats
Alka Vats
Table of Contents

Introduction to WebSockets:

In the early days of the internet, communication between web browsers and servers relied mainly on the request-response model using HTTP. While this approach worked well for traditional web applications, it posed challenges for real-time communication scenarios like instant messaging, live notifications, and online gaming. So, As technology evolved, the WebSockets protocol emerged as a powerful solution to facilitate real-time, full-duplex communication between clients and servers.

WebSockets offer a persistent connection between the client and server, enabling bidirectional data transfer. This means that data can flow in both directions simultaneously, allowing for real-time updates without the need for constant HTTP polling. WebSockets are particularly useful for applications that require low latency and live updates, making them an ideal choice for modern web applications.

Thus, In this blog, we will explore the fundamentals of WebSockets and implement a real-time chat application using JavaScript as an example. If you want to learn about the comparison between typescript and javascript, you can refer here.

Getting Started with WebSockets:

To use WebSockets in JavaScript, modern browsers provide a built-in WebSocket API that allows developers to establish WebSocket connections. The WebSocket API is supported in most modern browsers, including Chrome, Firefox, Safari, and Edge.

WebSocket Connection Process:

  1. Create a WebSocket instance: To initiate a WebSocket connection, you first need to create a new WebSocket object and specify the server’s URL that will handle the WebSocket connection.
  2. Connection Establishment: Once the WebSocket object is created, it tries to establish a connection with the server. During this phase, a WebSocket handshake takes place, where the client and server exchange headers to establish the connection.
  3. Open Event: If the connection is successfully established, the WebSocket object triggers an ‘open’ event. At this point, you can start sending and receiving data through the WebSocket.
  4. Data Transfer: After the connection is established, you can send and receive data in real-time using the WebSocket object’s send() method to send data to the server and handle incoming data using the onmessage event.
  5. Close Event: When the connection is closed either by the server or the client, the WebSocket object triggers a ‘close’ event.

Example: Real-Time Chat Application using WebSockets

In this example, we will build a simple real-time chat application using WebSockets. We’ll use HTML, CSS, and JavaScript to implement the client-side, and Node.js with the ws library to create the WebSocket server.

1. Setting Up the Project

Create a new project folder and set up the following files:

  • index.html
  • styles.css
  • client.js
  • server.js
2. HTML Structure (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-Time Chat</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="chat">
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="Type your message...">
    <button id="sendButton">Send</button>
  </div>
  <script src="client.js"></script>
</body>
</html>
3. Styling (styles.css)
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

#chat {
  max-width: 500px;
  margin: 20px auto;
  border: 1px solid #ccc;
  padding: 20px;
}

#messages {
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ccc;
  padding: 10px;
}

input[type="text"] {
  width: 80%;
  padding: 5px;
  margin-right: 10px;
}

button {
  padding: 5px 10px;
}
4. Client-Side Code (client.js)
const chatDiv = document.getElementById('chat');
const messageInput = document.getElementById('messageInput');
const messagesDiv = document.getElementById('messages');

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

socket.addEventListener('open', (event) => {
  showMessage('Connected to the chat!');
});

socket.addEventListener('message', (event) => {
  showMessage(event.data);
});

socket.addEventListener('close', (event) => {
  showMessage('Connection closed!');
});

function sendMessage() {
  const message = messageInput.value;
  if (message.trim() !== '') {
    socket.send(message);
    messageInput.value = '';
  }
}

function showMessage(message) {
  const messageElement = document.createElement('div');
  messageElement.textContent = message;
  messagesDiv.appendChild(messageElement);
}

document.getElementById('sendButton').addEventListener('click', sendMessage);
5. WebSocket Server (server.js)
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    // Broadcast the received message to all connected clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  ws.on('close', () => {
    console.log('Connection closed');
  });
});
6. Running the Application
  1. Install the ws package by running npm install ws in your project folder (where server.js is located).
  2. Start the WebSocket server by running node server.js.
  3. Open index.html in your browser.

Conclusion

WebSockets have revolutionized real-time communication on the web, enabling developers to create interactive and dynamic applications with low latency and reduced server load. In this blog, we covered the basics of WebSockets and demonstrated their implementation in a real-time chat application. As you continue your journey into web development, remember that WebSockets offer a powerful and versatile solution for building modern, real-time web applications. Happy coding!

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: