Web Sockets Part 1

Web Sockets Part 1

Web sockets is a communications protocol providing a full duplex (bi-directional) communication channel over a single T.C.P (Transport Control Protocol) connection. It can also be defined as a technology that allows a client to establish a two way communication with the server. Web sockets enable the client and server to create connections at the same time. According to MDN, Web Sockets is a technology that allows for opening an interactive communications session between a user’s browser and a server. With this technology, a user can send messages to a server and receive event-driven responses without requiring long-polling, i.e. without having to constantly check the server for a reply.

To fully understand the concept of web sockets, let us go back to the traditional HTTP (request and response) protocol. In this communication protocol the client makes a request and the server responds. For example imagine making a request to the server saying hey server, I’m expecting mail please have you seen it? The server responds saying “ not yet please keep asking” and if there’s an error, the server responds with an error message. With HTTP long-polling, the client continually polls the server requesting for new information. The server holds the request open until any new data is available, and responds with the new information once available. In essence, the client is constantly polling the server to see if the database has changed state. As soon as the client receives that new information, it can immediately send another request and the operation is continually repeated.

websockets (2).png

Web sockets on the other hand solves these little lapses from http by Allowing Full-duplex communication. client and server can talk to each other independently at the same time. This eliminates long-polling. Also, after upgrading the HTTP connection (handshake) in the beginning, client and server communicate over that same TCP connection throughout the lifecycle of Web socket connection and the bi-lateral communication continues until one party closes connection then it’s terminated.

websockets (3).png

Pros and cons of web sockets

pros

  1. It supports full duplex connection
  2. Cross platform compatibility (web, desktop, mobile)
  3. Web sockets have good security model (origin-based security model)
  4. Web sockets pass through most firewalls without reconfigurations

cons

  1. WebSockets are stateful so it's difficult to scale horizontally
  2. If application does not require a lot of dynamic interaction, HTTP is much simpler to implement.

uses of WebSockets

  1. chat apps
  2. collaboration tools
  3. Multi-player games
  4. Real time notifications app
  5. Location based apps

in the part 2 of this blog post, we will get our hands dirty and see how sockets work by writing some code... see you

1zgu.gif