I'm trying to create a NestJS microservice that can listen for data on a specific port. Following the instructions from here, I have the following for main.ts
:
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
const HOST = '127.0.0.1';
const PORT = 31123;
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.TCP,
options: {
host: HOST,
port: PORT
}
},
);
await app.listen();
}
bootstrap();
My app.controller.ts
looks like:
import { Controller, Get } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@MessagePattern('hello')
dataHandler(data: string) {
console.log(`Received: ${data}`);
}
}
I'm attempting to send data to the microservice via a Python script, running on the same computer:
import socket
HOST = '127.0.0.1'
PORT = 31123
someData = 'hello'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print(f'Sending: "{someData}"')
encodedString = someData.encode('utf8')
s.sendall(bytearray(encodedString))
The data never gets through; the log
message in the dataHandler
function in the microservice never executes. Am I specifying the message-pattern incorrectly, or are NestJS microservices not designed to handle raw TCP socket data? I've read this answer and this answer, but those deal more with message broker situations. Any help would be greatly appreciated.
CodePudding user response:
For anyone who lands here looking for a solution, I found the solution to this from this answer