×

Search anything:

Web Sockets vs HTTP

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we will dive deep into the world of 2 protocols that are the base communication of a lot of websites nowadays, what is a web socket? What is HTTP/HTTPS? What is the difference between web sockets and HTTP? How and where should I use them?

What is HTTP?

HTTP stands for Hypertext Transfer Protocol, pretty much every basic server that doesn’t have a very especific special need uses a HTTP protocol. So what is HTTPS protocol? When you search for a website and the website is loaded, formatted and all the actions of the web server are transmitted, the fact that the website is working and everything is going according to the website and server’s code has one main reason, HTTP protocol.

HTTP communication pattern

The HTTP requests originally runs in a request/response communication pattern, this means that the client request something and the server responds with the information it has.

For you to understand better let’s see a quick example, imagine you just posted a beautiful photo of you in front of your bedroom mirror, after a few minutes you realize that your underwear with watermelon drawings are on top of your bed, and it shows on the picture, so you go on the social media website click on the trash can icon besides the photo, reload the page and the photo is not there anymore.

What is the explanation for that? Request = you clicked on the trash can icon, response = the server processed the information that you wanted to delete the photo, went to the database and excluded the picture from it.

Pros and Cons of HTTP:

Pros of http:

  • It is a very simple protocol.

  • Easy to maintain.

  • A lot of content about it.

Cons of http:

  • Limited.

  • Administrative Overhead (multiple connections are created).

What is a Web Socket?

I’m sure you have been in a situation where you just downloaded an app and the first thing that pop’s up on your screen when you are opening it is a million-word text about the app terms and conditions. You scroll down to the bottom of the terms and agree, so you can use the app quickly.

The web socket communication protocol it’s nearly the same, the client accepts an agreement with the server to stay connected and share information with real-time updating and with the smallest possible latency.

This to way agreement is called a handshake, after this the client and the server can send and receive whatever they want, this handshake is ended when one of the sides disconnect and break the communication protocol.

Why use a WebSocket?

I’m imagining you ask yourself, “Why web socket were created if we already have request/response ?“.

Imagine we have a simple social media called “socketz” on the web, this social media was release just 1 day ago and a lot of people are posting pictures, texts and chatting with friends. The website has a word wide feed with real-time posts that are trending, this feed is constantly changing based on what the user likes, and what are the most liked posts, how would you quickly update this feed without making the user F5 every minute to make a new request?

The answer is exactly what you thought it would be: a bidirectional communication protocol that uses a TCP connection!

Explaining how the handshake works

To the handshake start we need to set a new URI (uniform resource identifier), that basically identifies a resource on the web, using WS or WSS (the parallel web socket versions of HTTP and HTTPS). The client starts the communication with a simple HTTP request and then requests to upgrade the connection based on the headers provided by the server. After that the server responds with the status code: 101 (Switching communication protocol), after that full duplex communication starts.

You remember that we just talked about the fact that this communication protocol starts after the client checks what are the headers of the HTTP request?

Well now we are going to take a look on how are these headers:

Client:

 GET /chat HTTP/1.1
    Host: socketz.server.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: <http://socketz.com>
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

Server:

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

You can see on this code 3 things that were pointed out on the explanation earlier, the first one is the HTTP/1.1 get request from the client that is the starting point of a web socket connection, second is the client asking for an upgrading of the protocol based on headers sent in advance, the last thing that I want to point out is the server response status code 101 switching protocol.

Creating a simple web socket with socket.io, express and node.js:

Now that we discussed that technical aspects of a web socket with examples and learn in depth about the protocol permission (handshake), we are going to create a really simple web socket with socket.io, express and node.js:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
    res.send('Connection Established');
});

server.listen(8080, () => {
    console.log('listening on port: 8080');
});

io.on('connection', (socket) => {
  console.log('user connected');
});

Run this code with ‘node. ‘.
The code is a very simple example, but socket.io can be a great library to create web sockets on node servers.

What are the pros and cons of a web Socket?

Pros of Web Sockets:

  • You don’t need to request constantly.

  • HTTP compatible.

  • Real-time request and response.

Cons of Web Sockets:

  • Hard to horizontally scale

  • Use cases are very particular.

Which protocol is better?

It all depends on what you are going to do, you may think HTTP protocol with request/respond communication may be the best because it’s simpler, but if you need a real-time app with a lot of requests you should use a web socket protocol.

Now to make sure you understood everything, let’s answer some questions:

Question

If you are building a blog with a lot of new posts, what would you use?

long polling
http
web sockets
server sent events
The correct answer is: HTTP protocol with common request/respond communication, bacause even though we have a lot of new post there is no need to create a web socket

Question

If you are building a blog with a lot of new posts, what would you use?

long polling
http
web sockets
server sent events
The correct answer is: Web sockets, because they are great for creating real-time connections with little to no latency.
Web Sockets vs HTTP
Share this