Implement simple Socket.io-client to Nestjs microservice

Kien Nguyen Ngoc
2 min readMay 12, 2021

Nestjs official document only guide of implementation socket.io server on nestjs. But in many project, you must connect to a socket.io server by your app. In this tutorial I will introduce how to implement socket.io-client to you Nestjs app. You can view code here

The idea behind this tut is use socket.io-client as a custom transporter.

To implement a new transport we need a strategy and a client proxy. Strategy is an object that will map you message handler with event fire from socket. And client proxy is a service that you can inject to any module to emit event to socket server.

At first we create a provider that contain object socket.io-client connect to socket server.

Then create strategy.

After that we can create a microservice with this strategy in main.js

Ok, by this way, transporter is created and we can listen incoming message by decorator MessagePatten

Create a new controller (only controller can add MessagePatten)

To testing purpose, we can create a simple socket.io server

Socket server will fire a message “welcome ” to new connection. And it listen to event “greeting” fire from client.

Run server and your Nestjs app will console:

And your server will receive:

But now, how can you emit message to server from other action. That why we need a client proxy

Create a new service SocketIoClientProxy

Then we can inject to a controller and call it:

Then go to your browser: http://localhost:3000/test-emit

Server will console:

ClientProxy support 2 method to use. There are emit and send. Emit like fire and forget while send give you a Observable, that you can implement model request-response.

I will introduce how to implement request-response model by socket.io next time, because it need to implement in both client and server.

The end. Thanks for your reading.

Reference:

Next stories about how implement request-response to socket.io-client: https://keyyuki.medium.com/implement-request-response-socket-io-client-to-nestjs-microservice-5651832486ef

--

--