Sling Academy
Home/JavaScript/Send and Receive Real-Time Data Using JavaScript WebSockets

Send and Receive Real-Time Data Using JavaScript WebSockets

Last updated: December 14, 2024

When developing modern web applications, the need for real-time data exchange between the client and server is common. This is where WebSockets come into play, offering a persistent, two-way communication channel over a single TCP connection. In this article, we'll explore how to send and receive real-time data using JavaScript WebSockets, providing clear examples and instructions.

Understanding WebSockets

WebSockets provide a full-duplex communication channel that allows for real-time data exchange. Unlike HTTP requests, where the client has to send a request to the server to get data, WebSockets allow either client or server to send a message at any time. This is critical for applications such as live chat, multiplayer games, and financial tickers.

The WebSocket protocol has two parts, first it establishes a handshake, and then it upgrades from HTTP to the WebSocket protocol. The server and client keep the connection open, reducing latency and allowing for quicker data transfer.

Setting Up a WebSocket Server

For demonstration purposes, we will set up a simple WebSocket server using Node.js. First, ensure you have Node.js installed on your machine.

// 1. Import the WebSocket library
const WebSocket = require('ws');

// 2. Create a new WebSocket server
two const wss = new WebSocket.Server({ port: 8080 });

// 3. Set up the connection event listener
 wss.on('connection', ws => {
  console.log('New client connected');
  
  // Send a welcome message to the client
  ws.send('Welcome to the WebSocket server!');

  // Listen for messages from the client
  ws.on('message', message => {
    console.log(`Received: ${message}`);
    // Echo the message back to the client
    ws.send(`You said: ${message}`);
  });

  // Handle client disconnects
  ws.on('close', () => {
    console.log('Client has disconnected');
  });
});

Save this file as server.js and run it using node server.js. This will start a WebSocket server on port 8080.

Creating a WebSocket Client

Now, let's create a simple HTML page that connects to our WebSocket server.

<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Client</title>
</head>
<body>
  <h1>WebSocket Client</h1>
  <input id="message" type="text" placeholder="Enter message" />
  <button onclick="sendMessage()">Send</button>
  <pre id="messagesDisplay"></pre>

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

    ws.onopen = () => {
      console.log('Connected to server');
    };

    ws.onmessage = (event) => {
      const messagesDisplay = document.getElementById('messagesDisplay');
      messagesDisplay.innerHTML += `Server says: ${event.data}\n`;
    };

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

Save this as an HTML file and open it in your web browser. Upon sending a message through the input field, you will notice that it is echoed back from the server.

Advantages of WebSockets

  • Low Latency: Real-time data transmission with negligible delay.
  • Efficient: WebSockets deliver data over the same connection created initially, minimizing header data overhead.
  • Bi-directional: Data can flow both ways freely once the connection is established.

Conclusion

Using WebSockets is a fantastic way to build real-time, interactive applications. With Node.js and a modern browser, setting up a WebSocket server and client is straightforward. We explored how to send and receive messages between a server and a client using WebSockets, demonstrating its capabilities for real-time communication in web applications. With this powerful tool in your toolkit, you can enhance user interactions and experiences on your web applications.

Next Article: Build Chat Apps and Multiplayer Games via JavaScript WebSockets

Previous Article: Create Persistent Sockets with the WebSockets API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration