TCP transport lets different parts of your app talk to each other using the TCP protocol. It helps send and receive messages over a network reliably.
TCP transport in NestJS
import { Transport } from '@nestjs/microservices'; const tcpOptions = { transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001 } };
The transport property must be set to Transport.TCP to use TCP transport.
You can specify host and port in options to define where the service listens or connects.
const tcpServer = app.connectMicroservice({
transport: Transport.TCP,
options: { port: 4000 }
});const client = ClientProxyFactory.create({
transport: Transport.TCP,
options: { host: 'localhost', port: 4000 }
});This code creates a simple TCP microservice that listens on port 3001. It waits for messages with the command 'sum' and returns the sum of the numbers sent.
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; import { NestFactory } from '@nestjs/core'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; import { Module } from '@nestjs/common'; @Controller() class AppController { @MessagePattern({ cmd: 'sum' }) sum(@Payload() data: number[]): number { return data.reduce((a, b) => a + b, 0); } } @Module({ controllers: [AppController] }) class AppModule {} async function bootstrap() { const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { transport: Transport.TCP, options: { port: 3001 } }); await app.listen(); console.log('TCP microservice is listening on port 3001'); } bootstrap();
TCP transport is good for fast and reliable communication but does not have built-in HTTP features like headers or REST.
Make sure the port you choose is free and not blocked by firewalls.
You can test TCP microservices using a TCP client or another NestJS client proxy.
TCP transport in NestJS helps microservices talk over the network using TCP sockets.
You set it up by specifying Transport.TCP and giving a host and port.
It is useful for fast, low-level communication between services.