Nestjs + Socketio 多人多房间聊天

版本:

"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "29.5.1",
"@types/node": "18.16.12",
"@types/socket.io": "^3.0.2",

 参考信息:

 // sending to sender-client only
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.emit('message', "this is a test");

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 io.in('game').emit('message', 'cool game');

 // sending to sender client, only if they are in 'game' room(channel)
 socket.to('game').emit('message', 'enjoy the game');

 // sending to all clients in namespace 'myNamespace', include sender
 io.of('myNamespace').emit('message', 'gg');

 // sending to individual socketid
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

实现方式:

建议最开始连接时就加入,我是在客户端每次都发送一个消息后加入的

client.join(roomId);

发送消息:

client.broadcast.to(roomId).emit('event-update', data);

 

// join
@SubscribeMessage('call-service-chats-get')
  async getMsgAChat(
    @MessageBody()
    data: {
      roomId: string;
      userId: string;
    },
    @ConnectedSocket() client: Socket,
  ) {
    return await new Promise(async (resolve, reject) => {
      await this.callServiceBaseService
        .getMeetingMsgByRoomId(data.roomId)
        .then((res) => {
          resolve({
            msg: '获取成功',
            success: true,
            data: res,
          });
        })
        .catch((e) => {
          Logger.error(e);
          reject({
            msg: '获取失败',
            success: false,
            data: [],
          });
        });
    });
  }

// 发消息给客户端
@SubscribeMessage('call-service-chats-add')
  async addMsgAChat(
    @MessageBody() data: CallServiceChatEntity,
    @ConnectedSocket() client: Socket,
  ) {
    return await new Promise(async (resolve, reject) => {
      await this.callServiceBaseService
        .saveMsg(data)
        .then((res) => {
          client.broadcast
            .to(data.roomId)
            .emit('call-service-chats-need-update', res);
          resolve({
            msg: '获取成功',
            success: true,
            data: res,
          });
        })
        .catch((e) => {
          Logger.error(e);
          reject({
            msg: '获取失败',
            success: false,
            data: [],
          });
        });
    });
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值