nestjs 集成websocket

  1. 当需要及时通讯的时候,我们需要集成websocket
    安装依赖

     npm install --save @nestjs/platform-ws @nestjs/websockets
    
  2. 建立websocket.gateway.ts

     import {
       WebSocketGateway,
       WebSocketServer,
       SubscribeMessage,
       MessageBody,
       OnGatewayConnection,
       OnGatewayDisconnect,
     } from '@nestjs/websockets';
     
     @WebSocketGateway()
     export class WebsocketsGateway
       implements OnGatewayConnection, OnGatewayDisconnect
     {
       handleDisconnect(client: any) {
         console.log('mmmmmllllllll', client);
       }
       handleConnection(client: any, ...args: any[]) {
         console.log('mmmmm', client);
       }
     
       @SubscribeMessage('message')
       handleMessage(@MessageBody() data: string): string {
         console.log('Received message from client:', data);
         // 会接收到web的send方法里面的data数据
         return 'Hello from server';
       }
     }
    
  3. 建立websocket.module.ts

     import { Module } from '@nestjs/common';
     import { WebsocketsGateway } from './websocket.gateway';
     
     @Module({
       providers: [WebsocketsGateway],
     })
     export class WebsocketModule {}
    

4.app.module.ts 引用

	@Module({
	  imports: [ WebsocketModule]
	 })
  1. main.ts 引用ws
    引入

     import { WsAdapter } from '@nestjs/platform-ws';
    
     async function bootstrap() {
       const app = await NestFactory.create<NestExpressApplication>(AppModule, {
         cors: true,
       });
       // websocket
       app.useWebSocketAdapter(new WsAdapter(app));
     }
    

web端使用方法

var ws = new WebSocket("ws://localhost:3000");
  //申请一个WebSocket对象,参数是服务端地址,同http协议使用http://开头一样,WebSocket协议的url使用ws://开头,另外安全的WebSocket协议使用wss://开头
  ws.onopen = function (e) {
    //当WebSocket创建成功时,触发onopen事件
    console.log("websocket连接成功",e);
  };
  ws.onmessage = function (e) {
    //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
    console.log("收到数据", e);
  };
  ws.onclose = function () {
    //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
    console.log("websocket已断开");
  };
  ws.onerror = function (error) {
    //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
    console.log("websocket发生错误" + error);
  };

  setTimeout(() => {
    const params = JSON.stringify({
      event: 'message', // => message对应着nestjs的@SubscribeMessage
      data: 'liping'
    }) 
    console.log(params)
    ws.send(params); //将消息发送到服务端
    // ws.send('{"event": "message", "data": "111111111" }')
  }, 3000)
  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_45610757

编写不易,请大家支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值