Heim > Fragen und Antworten > Hauptteil
我想使用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);
});