Insights

What are WebSockets, and How Do They Work?

2 min read Michael Carroll on Aug 17, 2023

PubNub WebSockets

provide new protocol between client and server which runs over a persistent
connection. Through this open connection, bi-directional, full-duplex messages can be sent between the single TCP socket connection (simultaneously or back and forth). Because it is an independent TCP-based protocol, it doesn’t ideally require HTTP tunneling (similar to Netflix and other streaming services), allowing for simplified communication when sending messages.

WebSockets come after many other technologies that allow servers to send information to the client. Web applications that use Comet/Ajax, push/pull and long polling all do this over HTTP. Other than handshaking the Upgrade Header, WebSockets is independent from HTTP.

WebSockets Diagram How do websockets work

What kind of apps can you build with WebSockets?

So why would you want to use WebSockets (or something like it)? It’s not really about WebSockets; it is about what you are trying to get down to the TCP layer, send and receive small data packages, and make it reliable and available across a number of devices.

Through the TCP connection, WebSockets can be used as a base for bi-directional real-time functionality. The ability to push a signal to a device as quickly as possible makes WebSockets one of the many solutions to push data between two devices. It’s the blueprint for creating real-time applications on both web and mobile (pretty much anything with a server and a client).

Pros and Cons of WebSockets

The WebSockets API and Protocol have both been standardized by the IETF and W3C, and have established themselves as a standard for real-time functionality in web, desktop, and mobile apps. Some advantages of WebSockets include:

  • Cross origin communication (however this poses security risks)
  • Cross platform compatibility (web, desktop, mobile)
  • Low weight envelope when passing messages

However, the designation of WebSockets as the standard for data push and real-time communication is somewhat of a misnomer around the web as it is described today. Independent of some open-source solutions, WebSockets are just a part of the puzzle when developing real-time applications. There are a slew of operational issues a developer may run into when using WebSockets as their real-time solution, especially as the app scales and the user base grows:

  • Network topology
  • Firewalls
  • Kernel configs
  • Load testing
  • Security
  • Monitoring
  • Scaling, redundancy,
, replication

Overall, WebSockets are a powerful tool for adding real-time functionality to a web or mobile application. Check out how you can take WebSockets to the next level with PubNub.

0