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.
Practice
Transport.TCP in a NestJS microservice?Solution
Step 1: Understand the role of Transport.TCP
Transport.TCP is used in NestJS to set up microservices communication over TCP sockets.Step 2: Compare with other options
Serving static files, database connections, and WebSocket handling are different concerns not related to Transport.TCP.Final Answer:
To enable communication between microservices using TCP sockets. -> Option CQuick Check:
Transport.TCP = Microservice TCP communication [OK]
- Confusing TCP transport with HTTP or WebSocket protocols
- Thinking it handles database connections
- Assuming it serves static files
Solution
Step 1: Check NestJS microservice creation syntax
The correct syntax usestransport: Transport.TCPand anoptionsobject withport.Step 2: Identify incorrect options
The other options use wrong properties likeprotocolinstead oftransport, passportdirectly without anoptionsobject, use string'tcp'instead of theTransport.TCPenum, or use the wrong transport type likeTransport.HTTP.Final Answer:
const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { port: 3000 } }); -> Option BQuick Check:
Use transport: Transport.TCP with options object [OK]
- Using 'protocol' instead of 'transport'
- Passing port directly without options object
- Using string 'tcp' instead of Transport.TCP enum
- Confusing TCP with HTTP transport
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
options: { host: '127.0.0.1', port: 4000 }
});
await app.listen();
console.log('Microservice is listening');What will be the output when the microservice starts successfully?
Solution
Step 1: Understand the code flow
The microservice is created with TCP transport on host 127.0.0.1 and port 4000, then listens successfully.Step 2: Identify the console output
Afterawait app.listen(), the console logs 'Microservice is listening'. No errors are shown.Final Answer:
Microservice is listening -> Option DQuick Check:
Successful listen logs message [OK]
- Assuming automatic HTTP server start
- Expecting error without port conflict
- Confusing TCP with HTTP output
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
options: { port: '3000' }
});
await app.listen();Solution
Step 1: Check the options object
The port value is given as a string '3000', but it must be a number.Step 2: Validate other parts
Host is optional, Transport.TCP is valid, and app.listen() can be awaited without callback.Final Answer:
Port should be a number, not a string. -> Option AQuick Check:
Port must be numeric type [OK]
- Passing port as string instead of number
- Thinking host is mandatory
- Expecting app.listen to require callback
Solution
Step 1: Set host and port correctly
To listen on all interfaces, host must be '0.0.0.0' and port 5000 is correct.Step 2: Attach client connection event properly
TCP microservice emits 'connection' event; attaching listener afterawait app.listen()is correct.Step 3: Evaluate distractors
Distractors either use the wrong host like'localhost', omit the host, fail to awaitapp.listen(), or attach the logger to thelisten()callback instead of the'connection'event.Final Answer:
const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '0.0.0.0', port: 5000 } }); await app.listen(); app.on('connection', () => console.log('Client connected')); -> Option AQuick Check:
Host 0.0.0.0 + event listener after listen [OK]
- Using 'localhost' instead of '0.0.0.0' to listen on all interfaces
- Logging inside listen callback instead of connection event
- Not awaiting app.listen() before event binding
Ready to prove it?
Pass the test and this pattern moves unknown
