/

Introduction to WebSockets

Introduction to WebSockets

WebSockets, as an alternative to HTTP communication in Web Applications, offer a long-lived bidirectional communication channel between the client and server. In this article, we will explore how to use WebSockets for network interactions.

Browser support for WebSockets

WebSockets are supported by all modern browsers. Check out the following image to see the browser support for WebSockets:

Browser support for WebSockets

How WebSockets differ from HTTP

WebSockets and HTTP are very different protocols in terms of communication. Unlike HTTP which is a request/response protocol, WebSockets provide the following advantages:

  • The server can send a message to the client without the client explicitly requesting it.
  • The client and server can talk to each other simultaneously.
  • Very little data overhead needs to be exchanged to send messages, resulting in low latency communication.

WebSockets are great for real-time and long-lived communications, while HTTP is better suited for occasional data exchange and interactions initiated by the client. Implementing WebSockets requires more overhead compared to HTTP.

Secured WebSockets

It is always recommended to use the secure, encrypted protocol for WebSockets, wss://. Avoid using the unsafe WebSockets version, ws:// (the equivalent of http:// for WebSockets), for obvious security reasons.

Creating a new WebSockets connection

To create a new WebSockets connection, use the following code:

1
2
const url = 'wss://myserver.com/something'
const connection = new WebSocket(url)

The connection variable refers to a WebSocket object. Once the connection is successfully established, the open event is fired. You can listen for this event by assigning a callback function to the onopen property of the connection object:

1
2
3
connection.onopen = () => {
//...
}

In case of any error, the onerror function callback is fired:

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

Sending data to the server using WebSockets

After the connection is open, you can conveniently send data to the server from within the onopen callback function:

1
2
3
connection.onopen = () => {
connection.send('hey')
}

Receiving data from the server using WebSockets

To receive data from the server, listen with a callback function on the onmessage event, which is called when a message event is received:

1
2
3
connection.onmessage = (e) => {
console.log(e.data)
}

Implementing a server in Node.js

The ws library is a popular choice for implementing WebSockets server in Node.js. It can also be used to implement a client and facilitate communication between two backend services. To use the ws library, install it using npm:

1
2
npm init
npm install ws

Here’s an example of the minimal code required to create a WebSockets server using ws:

1
2
3
4
5
6
7
8
9
10
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('ho!')
})

This code creates a new server on port 8080 (the default port for WebSockets) and adds a callback function when a connection is established. It sends the message ‘ho!’ to the client and logs the received messages.

Debugging WebSockets

Chrome and Firefox provide useful tools for visualizing the information sent through WebSockets. Their DevTools support is continually improving, with Firefox currently having the most informative debugging tool. To debug WebSockets in both browsers:

  • Open the Network panel in the DevTools.
  • Choose WS to filter only the WebSockets connections.

Here are screenshots of Firefox in action:

Firefox headers

Firefox detail

Firefox DevTools can provide even more information. In the example used for testing, you can inspect any sent data in a more organized fashion:

Data in Firefox

For more detailed instructions on using the Firefox WebSockets debugging tool, refer to this post on Mozilla Hacks.

Here is a screenshot of Chrome’s WebSockets debugging tool:

Chrome

tags: [“WebSockets”, “HTTP”, “network communication”, “real-time”, “bidirectional communication”]