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 the same you and your friend/colleague having a face to face conversation. Would you still start each of your text 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. Let us understand how these terms are significant.
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. As soon as your information is delivered, HTTP closes the connection.
It keeps the connection open for you so that you can exchange information over the same line until one of you closes the connection.
A 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.
4.5 (4,636 ratings)
View Course
You are right. As an end-user, the difference is not visible to you. Let’s think like an application developer. When I say open a secure line for information exchange, there is a process involved in it. This is commonly referred to as Handshaking. This is a process by which both the machines involved in a conversation agree to open a port to send and receive information. Now, these ports are blocked from one another and cannot be used for a third machine.
For handshaking, HTTP protocol sends and receives some extra bytes just to confirm whether a port is free in both the machines and fetches the details of the port. These extra bytes are an overhead when the frequent exchange of information is required. Hence, WebSocket.
When to use WebSocket and when not to?
By far, it is evident that it is useful only when the frequent exchange of information is required. It provides a duplex connection. This means that information can be sent and received at the same time. This obviously comes at the cost of blocking the port until the time information is exchanged. 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?
In its initial days, the Internet was a giant network of pages containing textual information. These were mostly static pages, which meant that information was constant and did not vary with subsequent retrievals. Over time, rich content such as images became an indispensable part of the web pages. The pages also became dynamic, which meant that now the information on the pages could be generated based on queries.
This led to the advancement in technologies with the invent 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 in time, either the client can send a request to the server or respond.
This gave way for 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 actually mean?
In HTTP, the request is always initiated by the client. 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.
Now to achieve bi-directionality, one must think that there are two connections maintained at every point in time. This is where WebSocket is different. It does this over a single TCP connection. This is termed as a full-duplex connection, meaning two-way communication over a single channel.
WebSocket Attributes, Events, and Methods
Let us create a WebSocket connection. The following command does this for us:
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 adhering to an optional protocol parameter.
1. Attributes
Once the connection is established, we have the following attributes in our Socket object:
i. 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 – Connection has been closed or could not be opened.
ii. Socket.bufferedAmount
A read-only attribute that tells the number of bytes that are queued using send() method.
2. Events
i. Socket.onOpen
An event triggered when a connection is opened.
ii. Socket.onMessage
An event triggered when the client receives a message from the server.
iii. Socket.onError
The event triggered an error in communication.
iv. Socket.onClose
The event triggered when a connection is closed.
3. Methods
i. Socket.send(data)
The send method transmits the data using the connection.
ii. Socket.close()
This method terminates the existing connection.
Example:
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 very popular website that uses WebSocket to push notifications whenever a new answer is available to the question.
Recommended Articles
This has been a guide to What is WebSocket? Here we discussed the basic concepts, attributes, events, along with a real-world example of WebSocket. You can also go through our other suggested articles to learn more –