WebSocket

WebSocket is a two-way (full-duplex) data transfer protocol on the web, allowing real-time data transfer between a web browser and a server. WebSocket allows a connection to be maintained between the client and the server, so information can be sent and received back efficiently and quickly without having to establish a new connection each time the information is transmitted. .

WebSockets are commonly used to develop real-time web applications such as online games, chat applications, and live data update applications. WebSocket is designed to replace other direct data transfer solutions such as Ajax or Comet, as it is more performant and more energy efficient.

Why WebSocket appeared

Duplex

A duplex communication system is a point-to-point system consisting of two or more connected parties that can communicate with each other in both directions. Duplex systems are used in many communications networks, providing simultaneous communication in both directions between two connected parties.

There are two types of duplex communication systems: full-duplex (FDX) and half-duplex half-duplex (HDX)

A duplex communication system is a point-to-point system composed of two or more connected parties or devices that can communicate with one another in both directions. Duplex systems are employed in many communications networks, either to allow for simultaneous communication in both directions between two connected parties or to provide a reverse path for the monitoring and remote adjustment of equipment in the field. There are two types of duplex communication systems: full-duplex (FDX) and half-duplex (HDX).

Half duplex

With traditional protocols HTTP/1.0 and HTTP/1.1 in the client-server model , the client sends an HTTP request to the server, the server processes and sends the results back to the client , including the HTML page as well as related information. mandarin. HTTP/1.0 is enough to make a request to get a document from a server.

With HTTP/1.1 adding reusable connections, the browser can initiate a connection to a web server to retrieve HTML pages, then use the same connection to retrieve resources such as images and text. writing, and so on. HTTP/1.1 reduces latency between requests by reducing the number of connections made from clients to servers .

By nature, HTTP is also half-duplex , meaning traffic flows in only one direction at a time, which is wasteful and inefficient.

A half-duplex (HDX) system provides communication in both directions, but only one direction at a time, not simultaneously in both directions.

Full duplex

Currently, web applications have developed far differently from the day they first appeared, along with countless new techniques applied to serve this process to bring a new, exciting and exciting experience. equally convenient for users.

Real-time web technology is becoming increasingly popular. There are many technologies and methods to help build real-time applications such as:

  • AJAX LONG-POLLING

  • SERVER SENT EVENTS (SSE)

  • COMET

  • WEBSOCKET

And today's technologies that require "real-time" or almost "real-time" can no longer meet half-duplex. Until now, the full-duplexWEBSOCKET format integrated in HTML 5 is dominant.

A full-duplex (FDX) system allows communication in both directions, and, unlike half-duplex, allows this to happen simultaneously.

How WebSockets Work

WebSockets work by establishing a persistent connection between the client and server over a single TCP socket. Once the connection is established, data can be sent and received in real-time between the client and server.

The WebSocket protocol consists of two parts: an initial HTTP handshake and the Web Socket protocol itself.

HTTP Handshake

The initial HTTP handshake is used to establish the WebSocket connection. The client sends an HTTP request to the server, specifying the WebSocket protocol in the Upgrade header. The server responds with an HTTP response that includes an Upgrade header indicating that it is switching to the WebSocket protocol.

WebSocket Protocol

Once the HTTP handshake is complete, the client and server can communicate using the WebSocket protocol. The WebSocket protocol is a simple, message-based protocol that allows for bi-directional communication between the client and server.

Messages are sent in frames, which consist of a header and a payload. The header contains information about the frame, such as the message type, length, and whether it is the final frame in a message. The payload contains the actual message data.

Uses of WebSocket

WebSocket is a network protocol that enables efficient real-time data transfer between web applications and servers. Uses of WebSocket include:

  • Implement real-time web applications: With the support of WebSocket, web applications can transmit and receive data between client and server quickly, continuously and continuously without having to refresh the page. Or send a new request.

  • Minimize system resources: Compared to using HTTP, WebSocket helps minimize system resources because the connection between the client and server will be kept open throughout the entire session.

  • Increased interactivity: With the ability to transmit data continuously and directly between client and server, web applications can increase interactivity and provide a better user experience.

  • Implementing multi-access applications: WebSocket makes multi-access web applications easier because multiple connections can be established between the client and server simultaneously.

  • Integration with big data streaming applications: With big data streaming capabilities, big data streaming applications can use WebSocket to transfer data more quickly and efficiently.

Advantages and disadvantages of WebSocket

WebSocket provides a more comprehensive, persistent way to transfer data between two parties, compared to traditional data transfer methods such as HTTP. Here are some pros and cons of WebSocket:

Advantages:

  • Faster response time: Because WebSocket allows a continuously open connection to be maintained between the client and the server, data transmission is performed faster than with HTTP.

  • Smaller data size: WebSocket reduces packet size and number of request/response communications compared to HTTP. Therefore, the transmitted data size will be smaller, reducing network traffic.

  • The right technology for real-time web applications: WebSocket is a suitable technology for real-time web applications such as online chat, online games, real-time data updates and similar applications. other users.

  • No need to send a new request to receive new data: When using HTTP, the browser must send a new request to receive new data from the server. However, with WebSocket, the server can send new data to the browser without having to make a new request.

Disadvantages:

  • Resource-intensive: WebSocket uses a persistent open connection between the browser and the server, so it is more resource-intensive than HTTP.

  • Not supported by some older browsers: Some older versions of browsers do not support WebSocket, which can make it difficult for developers to deploy their applications.

  • Lack of security features: Although WebSocket provides basic security features, it is still vulnerable to attacks.

WebSocket Structure

The usual standard protocol of WebSocket is ws:// , secure protocol iswss:// . The communication standard is String and supports buffered arrays and blobs.

WebSocket properties

Properties
Description

readyState

Describes connection status. It has the following values:

  • Value 0: connection has not yet been established (WebSocket.CONNECTING)

  • Value 1: connection established and able to communicate (WebSocket.OPEN)

  • Value 2: connection is going through the closing handshake (WebSocket.CLOSING)

  • Value 3: connection has been closed (WebSocket.CLOSED)

bufferedAmount

Represents the number of UTF-8 bytes that were queued using the send() method.

Example:

switch (socket.readyState) {
  case WebSocket.CONNECTING:
    // do something
    break;
  case WebSocket.OPEN:
    // do something
    break;
  case WebSocket.CLOSING:
    // do something
    break;
  case WebSocket.CLOSED:
    // do something
    break;
  default:
    // this never happens
    break;
}

WebSocket events

Event
EVENT HANDLER
Description

open

onopen

When a WebSocket enters the open state, “onopen” is called.

message

onmessage

When WebSocket receives data from Server.

error

onerror

There are any errors in communication.

close

onclose

The connection is closed. The events passed to “onclose” have three parameters: “code”, “reason”, and “wasClean”.

Event handlers can be created using the addEventListener() method. For example:

onopen

socket.onopen = function(event) {
  // handle open event
};

Using addEventListener()

socket.addEventListener("open", function(event) {
  // handle open event
});

onmessage

socket.onmessage = function(event) {
  var data = event.data;
  // process data as string, blob, or ArrayBuffer
};

Using addEventListener()

socket.addEventListener("message", function(event) {
  var data = event.data;
  // process data as string, blob, or ArrayBuffer
});

onerror

socket.onerror = function(event) {
  // handle error event
};

Using addEventListener()

socket.addEventListener("error", function(event) {
  // handle error event
});

onclose

socket.onclose = function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
};

handler onClose use event addEventListener()

socket.addEventListener("close", function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
});

WebSocket methods

Methods
Description

send()

send(data) sends data to the server. Message data is string, ArrayBuffer, blob.

close()

Close the existing connection.

Example:

var data = new ArrayBuffer(1000000);

// perform some operations on the ArrayBuffer
socket.send(data);

if (socket.bufferedAmount === 0) {
  // data sent
}
else {
  // data did not send
}

Use Cases for WebSockets

WebSockets are commonly used in a variety of real-time web applications. Here are some common examples:

Chat Applications

WebSockets are commonly used in chat applications to provide real-time messaging between users. With WebSockets, messages can be sent and received in real time, providing a fast and responsive chat experience.

Online Gaming

WebSockets are also used in online gaming to provide real-time communication between players and the game server. With WebSockets, game events can be sent and received in real-time, allowing for a more immersive and interactive gaming experience.

Real-time Dashboards

WebSockets can also be used to create real-time dashboards that display real-time data updates. With WebSockets, data can be pushed to the dashboard in real-time, allowing users to see the latest updates as they happen.

Financial Trading

WebSockets are commonly used in financial trading applications to provide real-time updates on stock prices and other financial data. With WebSockets, data can be sent and received in real-time, allowing traders to make informed decisions based on the latest market information.

Stream video and audio

WebSocket is also applied in the field of video and audio streaming to ensure data is transmitted continuously and without interruption.

Internet of Things (IoT)

WebSocket will help create a seamless and smooth connection between smart devices in a system.

Last updated