我最近开始与NestJs合作并在尝试使用NestJs microservices测试我的TCP client应用程序时获得了库存
是否可以使用非嵌套应用程序触发@EventPattern
或@MessagePattern()
?
尝试此方法时,套接字客户端只停留在trying to connect
上。
有任何想法吗?
谢谢。
您必须正确设置端口才能与嵌套一起使用:
您要发送的模式是
<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
。
在你的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
。