将套接字客户端与NestJs微服务一起使用

问题描述 投票:0回答:1

我最近开始与NestJs合作并在尝试使用NestJs microservices测试我的TCP client应用程序时获得了库存

是否可以使用非嵌套应用程序触发@EventPattern@MessagePattern()

尝试此方法时,套接字客户端只停留在trying to connect上。

有任何想法吗?

谢谢。

javascript node.js sockets microservices nestjs
1个回答
1
投票

您必须正确设置端口才能与嵌套一起使用:

您要发送的模式是

<json-length>#{"pattern": <pattern-name>, "data": <your-data>[, "id": <message-id>]}

例:

76#{"pattern":"sum","data":[0,3,3],"id":"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4"}

参数id用于@MessagePattern,没有它将触发@EventPattern

enter image description here

在你的main.ts中,你设置了嵌套服务器。这是您要从Packet Sender发送到的端口(输入1)。

const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.TCP,
  options: { host: 'localhost', port: 3005 },
  //                            ^^^^^^^^^^
});

那么你希望你的巢@Client听取来自Packet Sender的消息(见图像中的位置2)

@Client({
  transport: Transport.TCP,
  options: { host: 'localhost', port: 52079 },
  //                            ^^^^^^^^^^^  
})
private client: ClientTCP;

然后连接您的客户:

async onModuleInit() {
  await this.client.connect();
}

并定义一个@MessagePattern

@MessagePattern('sum')
sum(data: number[]): number {
  console.log(data);
  return data.reduce((a, b) => a + b, 0);
}

正如你所看到的,在我发送[0,3,3]的例子中,nest正确响应6

© www.soinside.com 2019 - 2024. All rights reserved.