Skip to content

ServerTCP

reference
1 min readUpdated

Kind: Class

Source: packages/microservices/server/server-tcp.ts

Part of: Microservices

ServerTCP is the TCP transport server implementation for NestJS microservices. It opens a TCP socket, registers message handlers by pattern, routes incoming packets to those handlers, and manages listening, error, and connection-close lifecycle events.

Extends: Server

Methods

MethodSignatureReturns
listenlisten(callback: (err?: unknown, ...optionalParams: unknown[]) => void)void
closeclose()void
bindHandlerbindHandler(socket: Socket)void
handleMessagehandleMessage(socket: TcpSocket, rawMessage: unknown)void
handleClosehandleClose()`undefined
unwrapunwrap()T
onon(event: EventKey, callback: EventCallback)void
initinit()void
registerListeningListenerregisterListeningListener(socket: net.Server)void
registerErrorListenerregisterErrorListener(socket: net.Server)void
registerCloseListenerregisterCloseListener(socket: net.Server)void
getSocketInstancegetSocketInstance(socket: Socket)TcpSocket

Properties

PropertyType
transportIdTransportId
serverNetSocket
portnumber
hoststring
socketClassType<TcpSocket>
maxBufferSizenumber
isManuallyTerminatedany
retryAttemptsCountany
tlsOptionsTlsOptions
pendingEventListenersArray<{ event: keyof TcpEvents; callback: TcpEvents[keyof TcpEvents]; }>

Where it refuses work

  • ServerTCP stops the work with Error when !this.server — “Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing…”.
  • ServerTCP stops the work with an early return when isUndefined((packet as IncomingRequest).id).
  • ServerTCP stops the work with an early return when this.isManuallyTerminated || !this.getOptionsProp(this.options, 'retryAttempts') || this.….
  • ServerTCP stops the work with an early return when this.maxBufferSize !== undefined && this.socketClass === JsonSocket.

Diagram

mermaid
graph LR
  Client[TCP Client] -->|Serialized message| Socket[TCP Socket]
  Socket --> ServerTCP[ServerTCP]
  ServerTCP -->|handleMessage| HandlerRegistry[Pattern Handler Registry]
  HandlerRegistry --> Handler[Message Handler]
  Handler -->|Response / Error| ServerTCP
  ServerTCP -->|Serialized response| Client

Usage

ts
import { ServerTCP } from '@nestjs/microservices';

const server = new ServerTCP({
  host: '127.0.0.1',
  port: 3001,
});

server.bindHandler(
  { cmd: 'sum' },
  async (data: number[]) => data.reduce((total, value) => total + value, 0),
);

server.listen(() => {
  console.log('TCP microservice listening on port 3001');
});

// Shut down gracefully when the process stops.
process.on('SIGTERM', async () => {
  await server.close();
});

AI Coding Instructions

  • Register handlers with bindHandler() before calling listen() so incoming patterns can be resolved immediately.
  • Keep handler patterns stable and serializable; TCP clients must send a matching pattern for handleMessage() to dispatch correctly.
  • Use listen() and close() for lifecycle management rather than interacting with the underlying TCP server directly.
  • Preserve error and listening listener registration during changes; registerErrorListener() and registerListeningListener() protect startup and connection lifecycle behavior.
  • Use unwrap() only when transport-specific access to the underlying Node.js TCP server is necessary.

How it works

ServerTCP is the TCP transport server implementation. It extends the shared Server base class, identifies itself as Transport.TCP, and creates either a Node TCP server or a TLS server to accept connections. packages/microservices/server/server-tcp.ts:33-43 packages/microservices/server/server-tcp.ts:172-185

Relationships

  • IMPORTS → Type
  • IMPORTS → isString
  • IMPORTS → isUndefined

Was this page helpful?

Download as PDF
ServerTCP — NestJS head-to-head