WebSocket is a network protocol that provides full-duplex (two-way), persistent communication over a single TCP connection. Unlike the traditional HTTP request-response cycle, WebSockets allow real-time data exchange between client (browser/app) and server.
This specification provides APIs to enable web applications to maintain bidirectional communications with server-side processes.
They enable features like live chat, online gaming, and live updates by letting the server push data to clients without constant polling, creating efficient, low-latency communication.
WebSocket API
A web application (e.g. web browser) may use the WebSocket interface to maintain bidirectional communications with a WebSocket server. 1
WebSocket communication starts with an HTTP handshake. Once the connection is upgraded, it stays open and both the client and server can push data independently at any time.
const socket = new WebSocket('wss://example.com/socket');socket.onopen = function(event) { console.log('WebSocket connection established'); socket.send('Hello server!');};socket.onmessage = function(event) { console.log('Message from server ', event.data);};socket.onclose = function(event) { console.log('WebSocket connection closed');};
In this guide we’ll walk through the implementation of a WebSocket-based ping application. In this application, the client sends a “ping” message to the server every second, and the server responds with a “pong” message. The client listens for “pong” messages and logs them, keeping track of how many message exchanges there have been.