# 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 <a href="#id-12-l-c3-bd-do-websocket-xu-e1-ba-a5t-hi-e1-bb-87n" id="id-12-l-c3-bd-do-websocket-xu-e1-ba-a5t-hi-e1-bb-87n"></a>

#### **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](https://en.wikipedia.org/wiki/Communication_system?ref=200lab.io) is a [point-to-point](https://en.wikipedia.org/wiki/Point-to-point_\(telecommunications\)?ref=200lab.io) 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](https://200lab.io/blog/http2-la-gi/) request to **the server**, **the server** processes and sends the results back to **the client** , including the [HTML](https://200lab.io/blog/html-la-gi/) 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-duplex**`WEBSOCKET` 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 <a href="#id-4-cong-dung-cua-websocket" id="id-4-cong-dung-cua-websocket"></a>

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 <a href="#id-5-uu-va-nhuoc-diem-cua-websocket" id="id-5-uu-va-nhuoc-diem-cua-websocket"></a>

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.&#x20;

### WebSocket Structure <a href="#cau-truc-websocket" id="cau-truc-websocket"></a>

![socket là gì?](https://topdev.vn/blog/wp-content/uploads/2019/06/websocket-la-gi.png)

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

### WebSocket properties

| Properties     | Description                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| readyState     | <p>Describes connection status. It has the following values: </p><ul><li>Value 0: connection has not yet been established (WebSocket.CONNECTING) </li><li>Value 1: connection established and able to communicate (WebSocket.OPEN) </li><li>Value 2: connection is going through the closing handshake (WebSocket.CLOSING) </li><li>Value 3: connection has been closed (WebSocket.CLOSED)</li></ul> |
| bufferedAmount | Represents the number of UTF-8 bytes that were queued using the send() method.                                                                                                                                                                                                                                                                                                                       |

&#x20;

Example:

```javascript
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`**

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

Using **addEventListener()**

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

**`onmessage`**

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

Using **addEventListener()**

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

**`onerror`**

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

Using **addEventListener()**

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

**`onclose`**

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

handler `onClose` use event **addEventListener()**

```javascript
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:

```javascript
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&#x20;

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.
