Sobes.tech
Middle

How is integration with WebSocket protocol implemented on the frontend?

sobes.tech AI

Answer from AI

Integration with WebSocket on the frontend is usually implemented using the built-in WebSocket object in browsers.

Main steps:

  1. Create an instance of WebSocket with the server URL, for example:
const socket = new WebSocket('wss://example.com/socket');
  1. Handle events:
  • onopen — connection established, data can be sent.
  • onmessage — data received from the server.
  • onerror — connection error.
  • onclose — connection closed.
  1. Use the send method to send data:
socket.send(JSON.stringify({ type: 'ping' }));
  1. To properly close the connection, call socket.close().

Example:

const socket = new WebSocket('wss://example.com/socket');

socket.onopen = () => {
  console.log('Connection opened');
  socket.send('Hello server!');
};

socket.onmessage = event => {
  console.log('Message received:', event.data);
};

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

socket.onclose = () => {
  console.log('Connection closed');
};

Thus, the frontend can exchange data with the server in real-time via WebSocket, which is useful for chats, games, notifications, and other interactive applications.