Websockets with Angular and NodeJs

Getting started with websockets in Angular and Nodejs is extremely easy. Thanks to the socket.io and ngx.socket.io libraries, we can send messages in real time from the server to the client and vice versa. We will create an application that communicates with a websockets server and is able to show us the connected users.

padymies
5 min readJun 4, 2021
title image

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to query the server for a response.

Communication via Websockets is bidirectional and full-duplex, meaning that both parties communicate and exchange data at the same time.

It is persistent and stateful communication. Unlike HTTP, the communication process does not end when the response to a request is received. Websockets keeps the connection open so that data can be shared without having to create a new connection.

These features make the use of Websockets ideal when constant, real-time data exchange is required, e.g. message chats, online games or positioning data.

For this example, we will use two libraries: socket.io for the node server and ngx-socket.io for the Angular client side. With these packages, it will be extremely easy to implement a bidirectional data flow between the two ends via websockets.

Server

For the server we will need to install the following libraries:

npm install express socket.io

user.ts

This class will be used to manage a list of users. It will allow us to obtain the list of users, add users and delete them.

index.ts

In this file we will configure the server. We will create an application with express, which we will pass to an http server by binding it to socket.io. In the io instance of socket.io we listen for the connection event to be fired when a client connects to the socket, receiving the connected client object.

After this, inside the connection, we will call the methods we prepared in the socket.ts. This part is important, because without it, we don’t register the events so that websocket knows to listen and emit to these calls.

Finally, we start the httpServer.

As seen in the code above, the first event heard on the socket is the “connection” event, which is fired automatically when a client connects. Within that event we will register the custom events that we have programmed.
In this case we have: disconnectClient, addUserOnline and removeUserOnline.

socket.ts

Here we will have the three previous methods that we registered in the index.ts.

Socket.io provides us with another listener event “disconnect”, which will fire when a client drops the connection to the websocket.

Registering events is easy, we just have to use the client object that we pass from the index.ts and call the on” method with the name of the event as the first parameter. Optionally you can pass a second parameter which will be an object with the data to send.

client.on('my-event', (data) => {});

The name given to the event is very important because we will have to replicate it at the other end. If we broadcast an “add-user” event on the server, the client will have to register a listener for that same event. If we emit from the client an event called “exit”, the server will have to be listening for that same event name.

To emit events, we have the possibility of doing it to all clients connected to the socket, to all clients except the sender, or to a particular client:

io.emit("Hello") => to all connected clientsclient.broadcast.emit("Hello") => to all connected clients except the senderio.to(client.id).emit("Hello") => to a particular client
Server-client communication

Client

For the client we will need to create an Angular application and add ngx-socket.io to the dependencies.

npm install ngx-socket-io

Once this is done, we are going to make the necessary configurations to be able to communicate with our server via Websockets:

In the AppModule we are going to import the SocketIoModule module passing it the configuration that will have the url and the port that we indicate in the server.

Then we will create a service that will be where we will put the logic that our client-side socket will have.

To do this we just need to import Socket from ngx-socket.io and inject it into the constructor. That’s it!
Now we can make use of two main methods:

  • emit: to send messages to the server, passing a mandatory first argument with the name of the event and an optional second argument with the data.
  • fromEvent: to receive messages from the server. This method takes a single argument with the name of the event we will listen for. Once the event is fired, it will return an Observable to which we will be subscribed to receive the data.

Note that the names of the events correspond to those we have registered in the server.

To make use of these methods we will create a simple view that will list, in real time, the connected users.

Finally, in the app.component.ts we will call the methods we had created in the socket.service.ts to get the list of users and broadcast when we connect or disconnect.

In the ngOnInit, through the rxjs concatMap operator, we obtain the id of our client to filter us in the list, and then we obtain the list of users that we store in the variable users$.

We also have the methods for joining or leaving the room: join() and exit().

Client-server communication

Let’s give it a try.

To test the application, open several windows in incognito mode and log in with different users, you will see how the list updates as they log in or out.

Conclusion

The example we have worked out is quite simple, but would follow the same logic for other uses. We just need to log the events and pass on the data we need, be it for instant messaging, real-time positioning, online gaming, or whatever you can think of.
I hope what you have read here has helped you, for any questions or suggestions you can leave comments on the post.

--

--

padymies

Software Developer. “Learn to share, share to learn”