Technology Sharing

Know and understand webSocket

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Today when I was browsing Niuke, I saw a big guy sharing that he encountered a problem about webSocket during a front-end interview. I realized that I had never seen this knowledge point before, so I quickly learned it and recorded it here!

WebSocket is a network communication protocol that provides a full-duplex communication channel, that is, the client and server can send and receive data at the same time. This is different from traditional HTTP requests, which are one-way, with the client initiating the request and the server responding to the request. WebSocket allows the server to actively send messages to the client, which makes real-time communication possible, such as online chat applications, real-time games, stock market updates, and other scenarios.

Basic Concepts of WebSocket

  1. Connection Establishment: The client initiates a WebSocket connection by sending an HTTP request, which contains a specific header indicating that this is a WebSocket handshake request.
  2. shake hands: After the server receives the request, if it supports WebSocket, it responds with an HTTP response, completes the handshake process, and establishes a WebSocket connection.
  3. data transmission: Once the connection is established, the client and server can send data over this connection. The data can be in text or binary format.
  4. Connection closed: Either party can close the WebSocket connection.

Steps to use WebSocket

  1. Creating a WebSocket Instance: On the client side, you first need to create a WebSocket instance and specify the server URL.

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