我目前正在与 socket.io 进行简单的聊天。基础知识已经可以工作,但现在我正在尝试实现 2 个不同的命名空间。我希望客户端能够通过单击按钮从一个命名空间(支持聊天)切换到另一个命名空间(朋友聊天)。
服务器端
//default namespace
io.on('connection', function(socket){
console.log('a user connected to the chat');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('client message', function(msg){
io.emit('server_message', msg);
});
});
//namespace /support
var sup = io.of('/support');
sup.on('connection', function(socket){
console.log('someone entered the support-chat');
socket.on('disconnect', function(){
console.log('user disconnected from support-chat');
});
//recieving and emitting message to all clients in namespace /support
socket.on('client message', function(msg){
console.log('message received: ' + msg);
io.of('/support').emit('server_message', msg);
});
});
//namespace /friends
var frnd = io.of('/friends');
frnd.on('connection', function(socket){
console.log('someone entered the friends-chat');
socket.on('disconnect', function(){
console.log('user disconnected from friends-chat');
});
//recieving and emitting message to all clients in namespace /friends
socket.on('client message', function(msg){
console.log('message received: ' + msg);
io.of('/friends').emit('server_message', msg);
});
});
客户端
var socket = io.connect();
//toggle namespace
$("#support_button").click(function(){
socket.disconnect();
socket = io('/support');
$('#messages').append($('<li>').text("You entered the Support-Chat"));
});
//toggle namespace
$("#friends_button").click(function(){
socket.disconnect();
socket = io('/friends');
$('#messages').append($('<li>').text("You entered the Friends-Chat"));
});
//sending message on submit
$('form').submit(function(){
socket.emit('client message', $('#m').val());
$('#m').val('');
return false;
});
//recieving message and display
socket.on('server_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
我认为开关本身正在工作,因为连接和断开事件正在按其应有的方式触发。但是,当涉及到向同一名称空间中的每个人发送消息(服务器已经从客户端收到消息)时,它不起作用。
这不是在特定命名空间中发出的服务器端调用吗?:
io.of('namespace').emit();
我是否误解了命名空间的用法?我想在两个主要聊天的命名空间“分割”之后立即实现房间,以获得支持和朋友。
或者我在服务器端实现了错误的名称空间?我认为 io.on(..)、io.of('/support').on(..) 和 io.of('/friends').on(..) 都以相同的方式工作并捕获他们自己的命名空间-客户端的事件。
非常感谢任何帮助!我觉得命名空间在“基本用法”文档中被忽视了。