JavaScript·100 questions

[ITEM 4] QUESTION: What is WebSocket?

Answer

WebSocket technology is radically different from the classic request-response model of the HTTP protocol. Instead of constantly opening a new connection for each action, WebSocket establishes a persistent, full-duplex connection between the client and the server over a single TCP connection.

To create such a connection in JavaScript, a built-in class is used. You simply initialize it by calling const socket = new WebSocket('ws://example.com/socket'), after which the browser initiates the handshake procedure to switch to the WebSocket protocol.

Managing the connection lifecycle is built on events. The WebSocket object has several key handlers. The onopen event fires immediately after the connection is successfully established. The onmessage event triggers every time new data arrives from the server. The onerror event records connection errors, and onclose reports that the channel has been closed.

To send text or binary data to the server, the send() method is used, which is called directly on the socket object. The server can send a message to the client at any time without a preliminary request from the client's side.

The main advantage of WebSockets is instant data transfer speed and minimal network overhead, since message headers are significantly smaller than HTTP headers. This technology is indispensable when developing interactive real-time applications such as chats, online games, financial market charts, collaborative document editing systems, and sports broadcasts.

Was this answer helpful?

More questions in this topic

Related questions from other topics