What is WebSocket?

Have you ever wondered what WebSocket is, and how to use Infura to make WebSocket requests? Learn more about key aspects of WebSocket, including the problems it solves, how it works, and how to use Infura with WebSocket.

What is WebSocket?

Using WebSocket and Infura

Have you ever wondered what WebSocket is, and how to use Infura to make WebSocket requests? This article covers key aspects of WebSocket, including the problems it solves, how it works, and how to use Infura with WebSocket.

What is a WebSocket?

A WebSocket is a persistent connection between a client and server. It builds over HTTP 1.1 using a TCP/IP socket connection. WebSocket is a binary protocol detached from HTTP after the initial WebSocket handshake.

In simple terms, WebSocket establishes a connection between the client and server, which stays open until the client and server agree to close it. The client and server can send and receive information concurrently with or without an order.

The following are some WebSocket use cases:

  • Live feed
  • Chatting
  • Showing client progress/logging
  • Multiplayer gaming
  • Dapp communication

In technical terms, a WebSocket is a stateful, persistent, full-duplex connection between a server and client using a single TCP/IP socket connection over HTTP.

Why do we need WebSocket?

Before learning about WebSocket, it’s essential to understand the background of the technology that gave birth to WebSocket: HyperText Transfer Protocol (HTTP).

HTTP is an application-layer stateless protocol that transmits hypermedia documents and communication between web servers and browsers. It uses a client-server model.

HTTP 1.0

HTTP 1.0 was released in 1995, and it defined how servers talked with clients and worked on the Transmission Control Protocol (TCP). In HTTP 1.0, the client makes a request, and the server responds. It worked great, but it was expensive, as it required server resources for each HTTP request. The biggest downside was that the server closed each request once it was fulfilled. This meant opening and closing individual HTTP requests -- slowing the whole process down.

HTTP 1.1

HTTP 1.1 solves the problem of resources as it enables the connection to stay open even after the server completed the initial client request. So, the server doesn’t close the request until asked to do so, and it can serve multiple requests without creating a new connection every time. In technical terms, HTTP 1.1 is keep-alive but uni-directional and stateless, which uses a persistent TCP connection.

HTTP 1.0 didn’t support open connections and required clients and servers to establish a TCP/IP socket connection each time they needed to send or receive data. HTTP 1.1 partially solves this by offering an open-connection, uni-directional, stateless connection using a persistent TCP connection. It works similar to UDP but with TCP reliability, allowing clients and servers to send and receive message-based data.

How does WebSocket work?

WebSocket starts its life using the standard HTTP request and response, but improves upon traditional HTTP-based technology. In WebSocket, after the initial HTTP request, once the server confirms and establishes the HTTP connection, the client asks for an upgrade using the 1.1 upgrade header. If the server supports and successfully switches the connection, it sends a successful status code 101. With the connection established, the communication starts. Next comes the data flow based on basic frame message protocol. Lastly, the connection is turned off when both client and server agree to turn off the WebSocket connection. WebSocket works only on HTTP versions 1.1 and higher.

ws:// and wss:// WebSockets handshake

WebSocket uses ws:// and wss:// instead of http:// or https://. The ws:// creates a standard WebSocket connection, whereas wss:// creates a secure connection. The other part of the URI remains the same.

The structure of the WebSocket URI is as follows:

"ws:" "//" host [ ":" port ] path [ "?" query ]
"wss:" "//" host [ ":" port ] path [ "?" query ]

The actual handshake looks like below.

Client

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Version: 13
Origin: http://www.example.com

Server

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

WebSocket example

Let’s look at the client code to create a WebSocket connection using JavaScript.

// New WebSocket object with ws URI paramter
const socket = new WebSocket('ws://app.example.com:23910/create');
// Code runs when WebSocket connection is opened
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0)
socket.send(getUpdateData());
}, 50);
};
// Code runs when data is received
socket.onmessage = function(event) {
handleUpdateData(event.data);
};
// Code runs when WebSocket is closed
socket.onclose = function(event) {
onSocketClose(event);
};
// Code runs when WebSocket closes due to an error
socket.onerror = function(event) {
onSocketError(event);
};

All the popular server technologies can handle WebSocket, including Nginx, Apache HTTP Server, Internet Information Services (IIS), and Lighttpd.

How does Infura use WebSockets?

Infura provides the tools and infrastructure that allow developers to easily take their blockchain application from testing to scaled deployment – with simple, reliable access to Ethereum and IPFS. Infura serves as the backbone for much of Ethereum’s blockchain development, supporting major DeFi outfits such as Uniswap and MakerDAO, the world’s most popular decentralized wallet, MetaMask, and NFT projects including Sorare and Async Art.

Infura provides access to consensus and execution clients, layer 2 networks, transaction relaying, Filecoin, and IPFS. Layer 2 networks don’t currently offer WebSocket support, but most other Infura networks do.

For example, you can use the Ethereum API to send WebSocket requests. You’ll need your Infura project ID to make API requests in Infura.

Use the following code to make a WebSocket request:

wscat -c wss://mainnet.infura.io/ws/v3/<YOUR-PROJECT-ID>
> {"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}

You can use WebSocket to subscribe to events on the Ethereum network. To learn more about using Infura with WebSocket, see the Infura documentation.

WebSocket pros and cons

Pros

  • HTTP compatible
  • Full-duplex (no polling)
  • Firewall friendly (standard)
  • Data can be sent and received faster than HTTP and AJAX
  • Compatible between platforms including mobile, desktop, and web

Cons

  • Stateful, difficult to horizontally scale
  • Proxying is tricky due to the complex setup process and associated troubleshooting
  • HTML5-compliant web browser required
  • WebSocket doesn’t support edge/intermediary caching

Conclusion

WebSocket is a vital web protocol that makes our current web more functional than ever. It’s also well-embedded within the web3 ecosystem as it enables technologies such as Infura to work efficiently and allow communications through a stateful, full-duplex, and persistent connection.