WebSocket: A Complete Guide

WebSockets Tutorial With Example | Getting Started With WebSockets

Web sockets are defined as two-way communication between the servers and clients, which means both parties can communicate and exchange data at the same time. WebSockets are the alternative to HTTP communication in Web Applications.

They offer a long-lived, bidirectional communication channel between the client and the server. Once established, the channel is kept open, offering a high-speed connection with low latency and overhead.

What is WebSocket?

Web socket protocol is being standardized, becoming a real-time communication between web servers and clients. In addition, web sockets are transforming to cross-platform standards for real-time communication between a client and the server.

The HTTP protocol has schemas, such as http and https. Web socket protocol also has a similar kind of schema defined in its URL pattern.

Web Socket is the independent TCP-based protocol, but it is designed to support any other protocol that traditionally runs only on top of the pure TCP connection.

The web Socket is the transport layer on the top of which any other protocol can run. The Web Socket API supports this ability to define the sub-protocols: protocol libraries that can interpret specific contracts.

Examples of such protocols include XMPP, STOMP, and AMQP. As a result, the developers no longer have to think of an HTTP request-response paradigm.

The only requirement on the browser side is to run the JavaScript code that can interpret the Web Socket handshake and establish and maintain the Web Socket connection.

On the server side, the industry standard is to use existing protocol libraries that run on top of TCP and leverage a Web Socket Gateway.

A simple example of initial request headers is as follows.

GET ws://websocket.appdividend.com/ HTTP/1.1
Origin: http://appdividend.com
Connection: Upgrade
Host: websocket.appdividend.com
Upgrade: websocket

How WebSockets differ from HTTP

HTTP is a different protocol, and also a different way of communicating. HTTP is the request/response protocol: the server returns some data when the client requests it.

In the WebSocket, the server can send a message to the client without the client explicitly requesting something.

A client and a server can talk to each other simultaneously.

Very little data overhead needs to be exchanged to send messages. This means low-latency communication.

Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, wss://.

The ws:// refers to the unsafe WebSockets version (the http:// of WebSockets) and should be avoided for obvious reasons.

Create a new WebSockets connection

To create a connection, use the new WebSocket() function.

const url = 'wss://appdividend.com/post'
const connection = new WebSocket(url)

The connection is a WebSocket object.

When the connection is successfully established, the open event is fired.

Attaching some event handlers immediately to the connection lets you know when the connection is opened, receive incoming messages, or if there is an error.

The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name, and the server accepts only one of the passed subprotocols in the array.

Accepted subprotocol can be determined by accessing the protocol property of the WebSocket object.

Listen for it by assigning a callback function to the onopen property of the connection object.

connection.onopen = () => {

If there’s an error, the onerror function callback is fired.

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)

Implement WebSocket on Node.js Server

Let’s take an example and implement the WebSocket on the Node.js server.

Create the project folder and inside that folder, create a file called server.js.

Also, open up the terminal and create a package.json file using the following command.

npm init -y

Then we need to install the ws library for WebSocket.

Implement WebSocket on Node.js Server

Then add the following code inside the server.js file.

// server.js

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  ws.send('Message From Server!!')

We created our server. Now, we need to create a client.

When the client is connected to the server, we will send and receive the message between the client and the server.

Go to the terminal and start the node server with the following command.

node server

Write the following code inside the client.js file.

// client.js

const WebSocket = require('ws')
const url = 'ws://localhost:8080'
const connection = new WebSocket(url)

connection.onopen = () => {
  connection.send('Message From Client') 

connection.onerror = (error) => {
  console.log(`WebSocket error: ${error}`)

connection.onmessage = (e) => {

We wrote the code that can connect the server WebSocket, and when the connection is open, we send a message to the server.

If the server has any message that needs to be received by a client, then it will also display the message on the client side.

Start a client-side server with the following command.

node client

At this time, we have started the two-node server.

  1. client.js
  2. server.js

The output is the following for client.js.

Create a new WebSockets connection

See the output.

Secured WebSockets

As soon as we have a connection to the server (when an open event is fired), we can start sending data to the server using the send(‘your message’) method on the connection object.

Two-way communication is done quickly.

That’s it.

1 Comment

  1. Thanks for this. I’ve been struggling because I’m a newbie at js. Perhaps it was because of that that one line in your blog lite me up: npn install ws –save. Then in VS Code, const WebSocket-reauire(‘ws’) led to
    const WebSocket=newFunction()
    function newFunction() {
    return require(“ws”);

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.