Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

WebSockets 101

Posted on Jun 24 • Originally published at syntackle.live WebSockets implement a full-duplex, bi-directional, TCP-based protocol, denoted by ws(s)://, which enables a persistent connection between the client and the Server.Back when websockets weren't a thing, HTTP polling was used for a similar purpose. HTTP is basically a uni-directional protocol wherein a client sends a request to the server, the server accepts the request and sends a response. The server can't send a response for which no request has been made by the client. In simple terms, it only responds to what it's asked for.This type of behavior poses a problem for real-time applications. What if the server needs to send some information to the client but the client doesn't know about it yet? It can't initiate a response without a request.To overcome these type of situations, a workaround is used, known as polling. The client assumes that there might be something that will be required later in time from the server and sends periodic requests at specific intervals to the server known as poll requests to check if there's something new. If there's nothing new for the server to send, it just responds with an empty response. This approach is known as short polling.Long polling is a similar approach as short polling except the fact that the server doesn't respond with an empty response on a poll request by the client. Instead, it receives the request, keeps the connection open, and only responds to it when there is actually something new that needs to be sent to the client. After the server sends a response with some data, the client sends another poll request either immediately or after a delay. That's how the server is actually able to initiate the communication which isn't possible in traditional HTTP protocol.Both of the above techniques have their own drawbacks which lead to the use of websockets.Websockets allow the client as well as the server to initiate the sending of messages. The websocket protocol involves a two-part process. The first part involves a handshake and the latter part involves the exchange of data.The initial handshake occurs when the client sends an HTTP 1.1 request to the server with an upgrade header set to websocket. This simply means that the client is informing the server that this connection isn't a normal HTTP connection, rather it needs to be upgraded to a websocket connection.The client's request looks something like this:The connection type in the above request is set to upgrade and the upgrade protocol is set to websocket. The upgrade header can only be used in HTTP 1.1 requests to upgrade to a different protocol.The sec-websocket-version, sec-websocket-key, and sec-websocket-extensions are special headers sent by the client to further describe the websocket connection.Now that the client request is sent, the server will verify the request (to make sure that it's a genuine websocket connection), accept the request if it supports a websocket connection, and return the verification response.Request verification is done as follows:The sec-websocket-accept header isn't the only thing which is required to know if the server has accepted the connection or not. There's also a status code of 101 which must be present to echo the acceptance of connection by the server. Any status code other than 101 tells that the websocket connection isn't complete.The server response looks something like this:Now, at this stage, both the client and the server are ready to receive messages from each other.The websocket instance has access to various events such as onopen, onclose, onmessage, etc. to perform some operations when these events occur.To better understand the flow of messages and various events, let's build a small application which implements websockets.In order to implement websockets, you can use a nodejs library named ws. It provides a fast and simple way to establish a websocket connection.Firstly, you need a server to handle websocket requests. The ws library provides an interface named WebSocketServer to create a websocket server.Then, you can start attaching events to this server.The above event will trigger whenever the server receives a new connection request from a client. It provides a callback function with the websocket instance (for a particular client) and the request object.You can use the request object to the sec-websocket-key header value, which I have used to identify a client. In production you must generate a unique id by yourself. This is just for demonstration purposes. Using the above code, you can log the client connection on the server.Next, let's see how you can broadcast a message to all clients connected to the server except the current client.So, here's a function that accepts a message object and broadcasts it to all clients except the one who is sending it.The websocket server — wsServer, has access to all the clients connected to it. The ws websocket instance itself describes the client. So, you can verify the client against the current ws instance and send the message accordingly.Also, the message should only be sent if the websocket connection is still open. If a client gets disconnected, the message will not be sent.But, what if we want to send a message only to the current client? For that, you simply need to do this:The error event of the websocket will allow you to log if anything goes wrong.Whenever a client sends a message to the server, the message event will get triggered by which you can broadcast the message to all the clients if you want to.The data you are getting in the message event will be a buffer, so you need to parse it into a string.You can also broadcast a client disconnected message to all of the connected clients on the event of disconnection of a specific client.A websocket client is nothing but a webpage with some client-side javascript. You must use the native WebSocket API provided by the browser to establish a websocket connection.The client's ws instance has access to the same events like open, close, message, etc. because it is essentially a websocket connection instance.Multiple browser instances (or tabs) connected to the same websocket server can serve the purpose of multiple clients.That's it. You can now send messages to the server and observe how they get broadcasted to multiple connected clients.Here's the github repository containing the entire code.Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Benny Code - Jun 5 Lucas Wolff - Jun 13 Femi Akinyemi - Jun 13 John Owolabi Idogun - Jun 4 Read our welcome letter which is an open invitation for you to join. Once suspended, this-is-learning will not be able to comment or publish posts until their suspension is removed. Once unsuspended, this-is-learning will be able to comment and publish posts again. Once unpublished, all posts by this-is-learning will become hidden and only accessible to themselves. If this-is-learning is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Murtuzaali Surti. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag this-is-learning: this-is-learning consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging this-is-learning will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

WebSockets 101

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×