What is a WebSocket?

What is Websocket, WebSocket advantages compared to HTTP, and case demonstrations.

WebSocket is a protocol for real-time communication that enables bidirectional communication between clients and servers, suitable for applications requiring low latency and high-frequency data updates.

How does WebSocket Work?

WebSocket is a protocol for full-duplex communication over a single TCP connection. It establishes a persistent connection between the client and server, allowing bidirectional real-time communication. WebSocket initiates a handshake using the HTTP protocol and then upgrades to a WebSocket connection, enabling both parties to send data directly. This persistent connection reduces communication overhead and enables the server to push data to the client actively, eliminating the need for frequent client-initiated requests.

WebSocket vs HTTP

  1. Reduced overhead: WebSocket requires less overhead compared to traditional HTTP connections, as it eliminates the need to repeatedly establish and tear down connections for each communication, reducing latency and conserving network resources.
  2. Bi-directional communication: WebSocket allows for simultaneous two-way communication between the client and server, which is particularly useful for real-time applications, enabling quicker data transfer and response times.
  3. Efficient data exchange: WebSocket supports binary data transfer, allowing for more efficient and compact data exchange, which is beneficial for multimedia streaming, gaming, and other applications requiring high-speed data transmission.
  4. Lower latency: By maintaining a persistent connection, WebSocket reduces the latency associated with establishing new connections for each data exchange, resulting in faster and more responsive communication.
  5. Server push capabilities: WebSocket enables servers to push data to clients without the need for clients to continuously poll the server for updates, leading to more efficient use of network resources and reducing unnecessary data transfer.

Overall, WebSocket's efficient use of network resources, reduced latency, and support for real-time, bi-directional communication make it a valuable tool for network optimization in various web-based applications.

Why use WebSocket?

WebSocket is used for real-time applications and services where low-latency, high-frequency data updates are required. It's especially useful for applications like real-time chat, online gaming, live sports updates, financial trading platforms, collaborative editing tools, and more. WebSocket enables faster and more efficient bi-directional communication between clients and servers compared to traditional HTTP, making it particularly well-suited for these types of use cases.

WebSocket Server (Node.js + ws)

const WebSocket = require('ws');
  
const wsk = new WebSocket.Server({ port: 8080 });
  
wsk.on('connection', ws => {
  ws.on('message', message => {
    console.log('Message received from client: %s', message);
      
    // Reply to client message  
    ws.send(`I am the server, and the message I received from you is: ${message}`);  
  });  
  
  ws.on('close', () => {  
    console.log('Client has disconnected');  
  });  

Client (JavaScript)

// Create WebSocket connection  
var socket = new WebSocket("ws://localhost:8080");  
  
// What to do when a connection is opened  
socket.onopen = function(event) {  
  console.log("Connection is open");  
  // Send an initialization message
  socket.send("I am the client and connected!");  
};  
  
// What to do when receiving server data  
socket.onmessage = function(event) {  
  console.log("The data received from the server is: " + event.data);  
};  
  
// What to do when a connection is closed 
socket.onclose = function(event) {  
  console.log("connection closed");  
};  
  
// How to handle connection errors  
socket.onerror = function(error) {  
  console.log("An error occurred: " + error);  
}

In addition to using WebSocket in JavaScript for front-end development, we can also use WebSocket in programming language platforms such as Java, C++, Go, Python, PHP, and Rust.

A Websocket Request Case

Here's an example of a typical WebSocket handshake request:

GET /chat HTTP/1.1         // a GET request to the /chat endpoint.
Host: example.com:8000     // the domain and port of the WebSocket server.
Upgrade: websocket         // the protocol that the client wishes to upgrade to.
Connection: Upgrade        // tells the server that the client wishes to establish a new connection rather than use an existing one.
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==       // a base64 encoded random value which server decode, hash it, and then send it back to prove that the server received the request.
Origin: http://example.com                        // the origin of the client request.
Sec-WebSocket-Protocol: chat, superchat           //specifies sub-protocols, if any used by the application creating the connection.
Sec-WebSocket-Version: 13                         // the WebSocket protocol version the client wishes to use.

In response to the handshake request, the server will return the following:

HTTP/1.1 101 Switching Protocols    // indicates that the protocol is being switched, as requested.
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=     // is a hash of the Sec-WebSocket-Key that was sent in the initial handshake, combined with a specific GUID. The client can use this to verify the server received the handshake

Conclusion

EdgeOne supports the WebSocket protocol that allows the server to send data to the client proactively. WebSocket provides a two-way communication channel over a single TCP connection allowing real-time data exchange. This is particularly beneficial for applications that need real-time interaction, such as interactive games, live chats, collaborative documents, etc.