Websockets with Express

Learn via video courses
Topics Covered

Overview

Say you're talking to your friend on the phone. Now that conversation is happening in real-time, implying that when you say something, your friend can hear it right away and respond immediately. That's kind of like how Websockets work in Express.js. They allow a website or app to communicate with a server in real-time, so that data can be sent and received instantly, without any delay. Now this differs from traditional web requests, which are more like sending a letter in the mail and waiting for a response to arrive. In this article, we shall learn more about this

What is a WebSocket?

Our client must send HTTP requests to send any messages or data to servers. The TCP protocol is used by the application protocol HTTP to establish a connection between the client and server. Once the data transfer is complete, the connection is terminated.

express-websocket1

Due to HTTP's unidirectional nature, there is only one method of communication between the client and server. Since HTTP is a stateless protocol, each request requires a three-way handshake, which adds latency to the response. However, since we are communicating in real-time, we cannot afford any delays. As a result, we demand that the client and server keep an ongoing connection. WebSockets will enable us to handle this situation.

express-websocket2

WebSocket is a full-duplex, bidirectional protocol as opposed to HTTP. Since it is a stateful protocol, it will maintain a connection between the client and server until one of them decides to break it. Because the connection is constant, real-time communication between the client and the server is possible.

The WebSocket communication protocol uses the "classic HTTP mechanism" of handshaking, which is implemented using request/response headers, to offer full-duplex communication channels over a single TCP connection between a web browser (client) and a web server.

By pushing data over the open connection and specifying ws and wss as the URI schemes used for unencrypted and encrypted connections, respectively, this enables the server to transmit material to the browser without being called by the client.

What is a ws library? A client and server implementation of the WebSocket protocol is provided by the Node ws library. It is a minimally overhead, high-performance library that is user-friendly for beginners.

The client could be compared to a browser. The client in this instance of the ws library, however, refers to a different backend program corresponding with our socket server. Additionally, the ws library cannot be used in our browser. The browser must have a native WebSocket object for it to function.

Example: Simple WebSocket Server Using Node.js and Express

express-websocket3

One can build real-time applications using WebSockets in Express that can support numerous clients and update in real-time without the need for repeated queries. It is a potent tool for creating interactive online apps, and it is worth looking at more.

Let's now see how we can create a simple WebSocket server using Node.js and Express

Let's understand this above code in depth,

The following code sets up express-ws on the said app. The global Router prototype for Express is modified

  1. The express-ws is set up on the Express application.
  2. If you are using a custom http.Server, pass it as an argument to the server so that express-ws can use it for WebSocket upgrade handlers. If you don't specify a server, express-ws will only work with the automatically created server from the app. Listen.
  3. option is an optional object that can contain: a) leaveRouterUntouched: set to true to prevent express-ws from modifying the Router prototype. You will have to manually apply .ws to every Router that you want to make available when this is enabled. b) wsOptions: an object of options passed to the WebSocketServer constructor. Required for WebSocket-specific features. This function returns a new object, referred to as wsInstance in the documentation.
  4. wsInstance.app contains the app where express-ws was set up.
  5. wsInstance.getWss() returns the underlying WebSocket server/handler. You can use wsInstance.getWss().clients to get a list of all connected WebSocket clients for this server. Note that this includes all clients, not just those for a specific route. Therefore, it is not recommended for broadcasts.
  6. wsInstance.applyTo(router) sets up express-ws on the given router or other Router-like objects. Use this method in two scenarios: a) When options.leaveRouterUntouched is enabled b) When using a custom router not based on the express. Router prototype. In most cases, this method is not necessary.

Handling Websockets with Express

The default library for WebSockets in Node.js is the ws npm module. The native http servers of Node.js are already supported by it.

The ws package is simple to integrate with Express. There are various libraries than the ws library that can aid in managing WebSockets in Express. Socket.io, a well-liked library for real-time, bidirectional communication between clients and servers, is one example of such a library.

For building a WebSocket server and managing WebSocket events with Express, socket.io offers a straightforward API.

Let's see how we can use Express and socket.io:

The connection, message, and disconnect events for a WebSocket server in Express are handled in this example using socket.io. The server logs a message to the console whenever a user connects to it. When the server receives a message from a client, it uses io. emit() to deliver the message to all clients that are currently connected and log it to the console. The server reports a message to the console whenever a user disconnects from the server.

Listening to Websockets with Express

The ws package supports native HTTP servers for Node.js. The listen() method of Express conveniently returns a native Node.js HTTP server. Therefore, you can employ the same procedure outlined in the WS Docs:

Testing

How exactly do you connect to this server? Along with the server implementation, ws also offers a WebSocket client implementation.

Conclusion

  1. The WebSocket communication protocol uses the "classic HTTP mechanism" of handshaking, which is implemented using request/response headers, to offer full-duplex communication channels over a single TCP connection between a web browser (client) and a web server
  2. The client could be compared to a browser. The client in this instance of the ws library, however, refers to a different backend program corresponding with our socket server. Additionally, the ws library cannot be used in our browser. The browser must have a native WebSocket object for it to function.
  3. io. emit() is used to deliver the message to all clients that are currently connected and log it to the console. The server reports a message to the console whenever a user disconnects from the server
  4. There are various libraries than the ws library that can aid in managing WebSockets in Express. Socket.io, a well-liked library for real-time, bidirectional communication between clients and servers, is one example of such a library