node.js - socket.io 分房间发送消息失败
高洛峰
高洛峰 2017-04-17 12:08:55
0
1
931

我想使用socket.io的分房间的功能,大致思路是刚进入页面就进入一个指定房间(由url决定的),然后后面的消息操作都是在这个房间下进行的,但是虽然进入房间能成功,但是发送消息时服务端接收到了,回发的信息客户端接收不到,求解,实现代码如下

服务端

io.on('connection', function(socket){
  socket.on('join', function(data){
    socket.id = data.accountid;
    socket.join(data.teamid);
    socket.emit('joined', data);
  });
  //接收前端发送过来的消息
  socket.on('sendMsg', function(data){
    if(data.to == 'all'){
      console.log(data);
      console.log(data.teamid + " received a message to all."); //测试有输出
      io.sockets.in(data.teamid).emit('replyMsg', data);
      console.log("success"); //测试时这里有输出
    }else{

    }
  });
});

客户端

var socket = io.connect();
    var currentteam = $(".teamBtn").data('teamid'),
        currentaccount = $(".nickname").data('accountid'),
        currentaccountNickname = $(".nickname").text();
    socket.emit('join', {
        teamid: currentteam,
        accountid: currentaccount
    });

    socket.on('joined', function(data){
        console.log(data.accountid + "joined room" + data.teamid + "succeed."); //测试时有输出
    });

    var $input = $("#inputContent");
    $input.keydown(function(e){
        if(e.shiftKey){
            if(e.keyCode == 13){
                socket.emit('sendMsg', {
                    accountid: currentaccount,
                    accountname: currentaccountNickname,
                    teamid: currentteam,
                    to: 'all',
                    msg: $input.val()
                });
                console.log($input.val() + "  sended.");
            }else{
                return ;
            }
        }else{
            return ;
        }
    });

    socket.on('replyMsg', function(data){
        console.log(data);
        alert(data);
    });
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
PHPzhong

I found the reason. socket.id = That sentence may have destroyed the socket and it will not be recognized later.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template