Nono.MA

WebSocket TypeScript client in the browser

MARCH 31, 2023

Here's how to connect and communicate with WebSocket servers from browser client applications using the WebSocket API and the WebSocket protocol.

// Create a WebSocket client in the browser.
const ws = new WebSocket("ws://localhost:1234");

// Log incoming messages to the console.
ws.onmessage = function (event) {
  // This runs when receiving message.
  console.log(event.data);
};

ws.onopen = () => {
  // This runs when we connect.
  // Submit a message to the server
  ws.send(`Hello, WebSocket! Sent from a browser client.`);
};

BlogCodeWebsocketTil