0
0
NestJSframework~5 mins

TCP transport in NestJS

Choose your learning style9 modes available
Introduction

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.

When you want to connect microservices inside your app using a fast and reliable network method.
When you need to send data between servers or services that are on different machines.
When you want to build a simple client-server communication using TCP sockets.
When you want to handle streaming data or continuous connections between services.
When you want to avoid HTTP overhead and use a lower-level network protocol.
Syntax
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.

Examples
This creates a TCP microservice server listening on port 4000.
NestJS
const tcpServer = app.connectMicroservice({
  transport: Transport.TCP,
  options: { port: 4000 }
});
This creates a TCP client that connects to the server on localhost port 4000.
NestJS
const client = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: { host: 'localhost', port: 4000 }
});
Sample Program

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.

NestJS
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();
OutputSuccess
Important Notes

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.

Summary

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.