Learn the Basics of Websocket with Me

heatherhaylett profile image Heather Updated on ・4 min read

I recently worked on two applications where my team wanted to implement an instant message feature allowing users to communicate in real-time. None of us had worked with WebSockets before so we decided it would be a great learning opportunity. Now that I’ve finished those projects I’m doing that thing where you go back and learn the basics of the tool you were using. While I was creating a chat feature with WebSockets, I definitely didn’t understand what magic was happening so I’m excited to explore in this blog post.

In this post, I’ll cover a basic review and history of how data is transferred over the web to create the webpage we see. Then I’ll dive into what WebSockets are and finish up with a demo I reproduced to help cement my knowledge.

Reviewing Client-Server Connections

As a user, when I go to a webpage I expect to see information and links I can click on or inputs where I can enter information. I move from page to page or receive new information based on an action that I took. Everything that is happening on the webpage is a result of the user doing something. Making a request and receiving a response is the basic setup of how a client communicates with a server. The server is reacting to a request from the client and historically, the client has always had to initiate the process.

HTTP, or Hypertext Transfer Protocol, is the protocol for transferring data through the client/server request and response model. HTTP can only allow a client to initiate a request to the server, a server cannot send information to the client without being asked.

Alt Text

In relation to how information shows up on a webpage, if we want to display data from the server we need to ask for it, then the server sends it to the client, and the client has to show the new data by accepting the information and refreshing the page. This back and forth of requests and responses can slow down an application. So what if there was an open connection between the client and server to continuously send and receive data? Websockets achieve this functionality for us.

Defining Websockets

Real-time web is when a client receives data as soon as it’s published and doesn’t need an update to get that response. Websocket is a protocol that keeps the connection between client and server open for persistent data exchange. WebSockets are a fairly new technology but quickly becoming an industry standard.


I mentioned earlier that I had used WebSockets for an instant messaging feature. Websocket data transfer is great for short messages, news updates, etc. really any kind of data that changes frequently. That being said, it’s important to note that WebSockets will not replace HTTP in your server rather it enhances HTTP protocol.

To create the WebSockets bi-directional connection between client and server, the client must first initiate a request to the server with what is known as a WebSocket handshake request. This handshake request contains an upgrade WebSocket header telling the server to switch to bi-directional protocol.

In each project, I used a different library for writing features that utilize WebSockets. The services my team used were Socket.io and Pusher. I didn’t have a preference between the two as I mentioned before I wasn’t totally sure of what was happening under the hood. I just knew they were making neat things happen in my application. As I continue building applications, I’ll be interested to further explore the capabilities of both.

Build a Websocket Connection

I followed a demo from ably.io that me to understand the process of establishing a WebSocket connection.

The first step is to construct a WebSocket using the new WebSocket() method. This demo uses (websocket.org)[websocket.org] to host a WebSocket Echo server.

  // create a new WebSocket
  const socket = new this.WebSocket('ws://echo.websocket.org');

Next we use onopen to open the WebSocket connection

  // show a connected message when the WebSocket is opened
  socket.onopen = function(event) {
    socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
    socketStatus.className = 'open';

To send a message to the server we use send and add it to our chat box for other users to see.

  // add message to list of messages
  console.log('sent from client: ' + message);
  messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message + '</li>';

Lastly, we need to tell the server to fire an event when the message is received with onmessage.

  socket.onmessage = function(event) {
    const message = event.data;
    console.log('received: ' + message);

On the page it looks like this:

WebSocket demo on page

Resources Used
What are WebSockets? from pusher.com
A Beginner's Guide to WebSockets from freeCodeCamp
WebSockets from ably.io

Posted on by:

heatherhaylett profile



I’m interested in building technologies that impact others' quality of life, particularly through web accessibility, UI, and API architecture. Twitter: @heather_haylett


markdown guide