Updated June 1, 2023
What is WebSocket?
Picture yourself writing an email to a friend or a colleague. You always start with Hi <friend>, followed by the context, and end with a Thanks <name>. Now imagine you and your friend/colleague having a face-to-face conversation. Would you still start each of your texts with Hi and end with Thanks? A big NO, right? That practically sums up HTTP and WebSocket.
Technical Understanding
It is a two-way communication protocol. It provides a full-duplex connection.
- Looking back at our example of emails and face-to-face conversations, emails signify HTTP protocol, while face-to-face conversations signify WebSocket protocol. This doesn’t mean that emails are sent over HTTP protocol, no. Emails mostly use SMTP protocols, but let’s not worry about that for now. The essential takeaway from the example is the opening and closing of the underlying connection between the two parties exchanging information.
- HTTP exchanges information by opening a new connection on every request-response cycle. So every time you send a request or receive a response, HTTP establishes a new connection. Think of a connection as simply a secure line to transfer information. HTTP closes the connection immediately after delivering your information. It keeps the connection open so you can exchange information over the same line until one of you closes the connection.
Little More Technical
Okay, I get it all about the connection being left open. How does it help me? I feel no difference whether I am sending emails or sending chat messages. You are right. As an end-user, the difference is not visible to you. Let’s think like an application developer. Opening a secure line for information exchange involves a process commonly referred to as handshaking. In this process, both machines in a conversation agree to open a port for sending and receiving information. These ports block each other, and a third machine can’t use them.
For handshaking, the HTTP protocol sends and receives some extra bytes to confirm whether a port is free in both machines and fetches the details of the port. Frequent information exchange requires these extra bytes as overhead. Hence, WebSocket.
When to use WebSocket and When not to?
You only find it helpful when requiring frequent information exchange. This is because it provides a duplex connection. This enables the simultaneous sending and receiving of information. This blocks the port until the information exchange completes. So, using WebSocket is a trade-off between saving crucial bytes and enabling faster conversations at the cost of blocking a port for longer.
The best use-case of WebSocket is when you need real-time data really quick, like stock prices. Stock prices change every second. So, using HTTP would waste crucial time in unnecessary handshaking, and the quotes would get stale. Instead, use this and get it done quicker. Contrarily, if you can afford a delay of a few milliseconds in the information you seek, you must go for HTTP.
How WebSocket came into Being?
The Internet was a giant network of pages containing textual information in its initial days. These were mostly static pages, meaning the information was constant and did not vary with subsequent retrievals. Over time, rich content like images became indispensable to web pages. The pages also became dynamic, which meant that the information could now be generated based on queries.
This led to technological advancement with the invention of Dynamic HTML, JavaScript, etc. They all were very advanced but used HTTP protocols. The problem with HTTP protocols – the connection was not duplex. The communication was unidirectional. At any point, the client can send a request to the server or respond. This gave way to WebSocket protocols allowing a full-duplex connection to enhance the user experience.
Understanding the Term ‘Full-Duplex’
We have been coming across the term full-duplex quite a lot. What does this mean? In HTTP, the client always initiates the request. This means that unless the client sends a request, the server will not respond. This makes communication unidirectional.
While in WebSocket, both the client and server can push messages to each other at the same time. The client need not make a request each time it requires some response. This makes the connection bi-directional. To achieve bi-directionality, maintain two connections at every point in time. This is where WebSocket is different. It does this over a single TCP connection. This is termed a full-duplex connection, meaning two-way communication over a single channel.
WebSocket Attributes, Events, and Methods
Let us create a WebSocket connection.
Code:
var Socket = new WebSocket(URL, [protocal] );
The new WebSocket method is the exposed API method that returns an established connection with the URL specified as the first parameter and adheres to an optional protocol parameter.
1. Attributes
Once the connection is established, we have the following attributes in our Socket object:
a. Socket.readyState:
A read-only attribute that tells the state of the connection.
0 – Connection has not yet been established.
1 – Connection is established, and communication is possible.
2 – Connection is going through a handshake.
3 – The connection has been closed or could not be opened.
b. Socket.bufferedAmount: A read-only attribute that tells the number of bytes that are queued using send() method.
2. Events
a. Socket.onOpen: An event is triggered when a connection is opened.
b. Socket.onMessage: An event is triggered when the client receives a message from the server.
c. Socket.onError: The event triggered a communication error.
d. Socket.onClose: The event is triggered when a connection is closed.
3. Methods
a. Socket.send(data): The send method transmits the data using the connection.
b. Socket.close(): This method terminates the existing connection.
Example:
Code:
var socket = new WebSocket(“ ws://echo.websocket.org ”);
if (socket.readyState === WebSocket.OPEN){
socket.send(“Hello World”);
}
if (socket.readyState === WebSocket.OPEN){
socket.close( );
}
Real-World Example
StackOverflow is a viral website that uses WebSocket to push notifications whenever a new answer is available to a question.
Recommended Articles
This has been a guide to What is WebSocket? Here we discussed the basic concepts, attributes, events, and a real-world example of WebSocket. You can also go through our other suggested articles to learn more –