DEV Community

Cover image for What's exactly Websockets
Ahmed Ossama
Ahmed Ossama

Posted on

What's exactly Websockets

In this article we will talk about websockets, it is a computer communication protocol, providing full connections over a single TCP connection.
Before we dive deeper into how it works, let’s discuss briefly on how HTTP works to know why we have web sockets!

How HTTP works? (http:// , https://)

Consider having a client and a server, the following flow will show us how the communication occur :

  • The client opens a TCP connection to communicate with the server.
  • The client sends a request to the server for example a GET request for an index.html file
  • The server responds to that request with a certain status code such as:404 not found or 201 ok. And this flow continues until the client closes the connection. We can conclude here that this protocol is unidirectional as we can’t receive a response without sending a request and vice versa. Image description

Now we knew how http works, but in many situations this protocol will overhead, imagine we are having an application like facebook, while you are browsing there’s notifications maybe pop up, guess :
Is it good to be fetched using HTTP?
Here you as a client don’t know that the resource is modified because another user modified it or the service itself modified it, so in this case using HTTP is not the best thing, HTTP will be preferred when a resource that changes hourly or changes only after it knows that a related resource is modified, so that we need something STATEFUL.

How does websocket work? (ws:// , wss://)

Having the same client and server :

  • The client opens a TCP connection.
  • A websocket handshake request occurs, this is a normal http request with upgrade header that asks the server whether to establish a websocket connection or not.
  • If it’s ok:
    • The client now is able to send and receive information to and from the server without waiting, then this is a bidirectional protocol.
    • If anyone closes the connection, the other will not be able to send information and the connection is terminated from both sides. Image description

When to use websockets?

There are some scenarios where websockets are preferred over HTTP such as Fast Reaction Time, Ongoing Updates.
It’s used in:

  • Chat Applications
    *Consider a chat application that allows multiple users to chat in real-time. If WebSockets are used, each user can both send and receive messages in real-time. Anyone can send you a message without requesting to receive it!

  • Real time Applications

    • Consider a notification system in a feed application as we talked earlier.
  • Gaming Applications

    • Consider having a multiplayer game running in the browser which its ui is automatically updated upon the current state.

Pros of using websockets

  • Full duplex
    • No polling required and we don’t have to ask for a response repeatedly.
  • Moderate overhead in establishing connection, and minimal overhead in sending/receiving messages.
  • Secure. ## Cons of using websockets
  • Since it’s stateful it’s difficult to be horizontally scaled.

Implementing a websocket

We will use python and js to write a very simple websocket to establish connection between a created server and the browser client side.
First of all, implement the server in python language that recieves a messages and instantly reply to it.
Don't forget to "pip install websockets"
Create a folder and place this script file in it.

import asyncio

import websockets

# create handler for each connection

async def handler(websocket, path):

    data = await websocket.recv()

    reply = f"Client:{data}\nServer:I am fine, thanks!"

    await websocket.send(reply)



start_server = websockets.serve(handler, "localhost", 7000)



asyncio.get_event_loop().run_until_complete(start_server)

asyncio.get_event_loop().run_forever()
Enter fullscreen mode Exit fullscreen mode

Second, implement the client side using html and js

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Client</title>

</head>

<body>

    <button onclick="contactServer">How are you?</button>

</body>

<script>

    const socket = new WebSocket('ws://localhost:7000');

socket.addEventListener('open', function (event) {

    socket.send('How are you?');

});



socket.addEventListener('message', function (event) {

    console.log(event.data);

});

const contactServer = () => {

    socket.send("Initialize");

}

</script>

</html>
Enter fullscreen mode Exit fullscreen mode

After running the file and opening the HTML page, the results as follow
Image description

Conclusion

Finally, each technology has its pros and cons and using websockets or http depends on the nature of your application and the requirements needed.
If you only want to receive an update every hour, you will want to go with HTTP. If you want to receive updates every second, a WebSocket might be a better option, because establishing an HTTP connection takes a lot of time.

Top comments (0)