最近做个需求使用到ws,nest官网ws,记录一下遇到。
创建项目
nest new appdemo
安装
npm i --save @nestjs/websockets
在 Nest 中,网关只是一个用 @WebSocketGateway() 装饰器注解的类。从技术上讲,网关与平台无关,这使得它们在创建适配器之后就可以与任何 WebSockets 库兼容。有两个开箱即用的WS平台:socket.io和ws。你可以选择最适合你需要的
使用
src目录下创建ws.gateway.ts
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WsResponse } from "@nestjs/websockets";
import { Socket } from "dgram";
// 注意ws端口号不能和http端口号一样,否则会冲突
@WebSocketGateway(3002)
export class WsStartGateway {
// SubscribeMessage里面的字符串代表类型,就是send event的值
@SubscribeMessage('events')
handleEvent(
@MessageBody() data: string,
@ConnectedSocket() client: Socket,
): WsResponse<unknown> {
console.log('ws hello data', data);
const event = "events";
return {
event,
data: {
msg: 'ws 收到信息后返回'
},
};
}
}
需要注意:
- ws端口号不能和http端口号一样,否则会冲突。WebSocketGateway(port)写端口号
- SubscribeMessage里面的字符串代表类型,就是send event的值
app.modules.ts中添加到providers
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { WsStartGateway } from './ws.gateway';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService, WsStartGateway],
})
export class AppModule { }
main.ts
import { NestFactory } from '@nestjs/core';
import { WsAdapter } from '@nestjs/platform-ws';
import { AppModule } from './app.module';
const port = '3000';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 全局配置跨域
app.enableCors({
// 允许的请求源
origin: '*'
});
app.useWebSocketAdapter(new WsAdapter(app));
await app.listen(port);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
前端使用
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
function createWs() {
const ws = new WebSocket('ws://localhost:3002')
ws.addEventListener('open', (event) => {
console.log('ws 连接成功', event)
ws.send(
JSON.stringify({
event: 'events',
data: '测试ws 发送数据 hello',
})
)
})
ws.addEventListener('message', (event) => {
const data = event.data
console.log('ws message data', data)
})
ws.addEventListener('error', (event) => {
console.log('ws 连接失败', event)
})
}
createWs()
// 适当时机关闭ws
// ws.close()
</script>
</html>
注意:
- ws.send() 参数是string,需要JSON.stringify。event的值要和SubscribeMessage值保持一致