JAVASCRIPT

Establishing Real-time Communication with WebSocket API

Learn to open a WebSocket connection to an API, send messages, and receive real-time data for dynamic and interactive web applications.

function connectToWebSocket(url) {
  const ws = new WebSocket(url);

  ws.onopen = () => {
    console.log('WebSocket connection established.');
    // Send a message after connection is open
    ws.send('Hello Server!');
  };

  ws.onmessage = (event) => {
    console.log('Message from server:', event.data);
    // Handle incoming real-time data here
    try {
      const data = JSON.parse(event.data);
      console.log('Parsed JSON data:', data);
    } catch (e) {
      console.log('Received non-JSON data or parsing error.');
    }
  };

  ws.onerror = (error) => {
    console.error('WebSocket error observed:', error);
  };

  ws.onclose = (event) => {
    if (event.wasClean) {
      console.log(`Connection closed cleanly, code=${event.code}, reason=${event.reason}`);
    } else {
      console.error('Connection died (e.g. server process killed or network down)');
    }
    // Implement re-connection logic here if desired
  };

  return ws; // Return the WebSocket object for external control
}

// Example usage:
// const myWebSocket = connectToWebSocket('ws://localhost:8080/ws-path');
// To send messages later:
// if (myWebSocket.readyState === WebSocket.OPEN) {
//   myWebSocket.send('Another message!');
// }
// To close the connection:
// myWebSocket.close();
How it works: This JavaScript snippet demonstrates how to establish and manage a real-time WebSocket connection. Unlike traditional HTTP requests, WebSockets provide a persistent, full-duplex communication channel between a client and a server, enabling instant data exchange. The code sets up event listeners for `open`, `message`, `error`, and `close` events, allowing you to react to the connection's lifecycle, send data to the server, and process incoming messages in real time. It also includes basic logic for handling both clean and unclean disconnections.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs