将 NestJS 连接到 websocket 服务器 [英] Connect NestJS to a websocket server
本文介绍了将 NestJS 连接到 websocket 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
NestJS 如何作为 websocket 客户端使用?我想使用 NestJS 作为客户端连接到远程 websocket 服务器,但我在框架中没有找到有关此实现的任何信息.
How can NestJS be use as a websocket client? I want to connect to a remote websocket server as a client using NestJS, but I didn't find any information about this implementation in the framework.
推荐答案
由于 Nestjs 只是 Nodejs 的一个框架,所以需要找到支持 Websocket 的 NPM 包.例如,我使用 ws
和 @types/ws
类型定义,并创建一个 Websocket 客户端作为 Nestjs 服务类:
As Nestjs is simply a framework for Nodejs, so you need to find an NPM package that supports Websocket. For example, I use ws
with @types/ws
type definition, and create a Websocket client as a Nestjs service class:
// socket-client.ts
import { Injectable } from "@nestjs/common";
import * as WebSocket from "ws";
@Injectable()
export class WSService {
// wss://echo.websocket.org is a test websocket server
private ws = new WebSocket("wss://echo.websocket.org");
constructor() {
this.ws.on("open", () => {
this.ws.send(Math.random())
});
this.ws.on("message", function(message) {
console.log(message);
});
}
send(data: any) {
this.ws.send(data);
}
onMessage(handler: Function) {
// ...
}
// ...
}
// app.module.ts
import { Module } from "@nestjs/common";
import { WSService } from "./socket-client";
@Module({
providers: [WSService]
})
export class AppModule {}
这篇关于将 NestJS 连接到 websocket 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文