我目前正在使用socket.io开发一个简单的聊天应用程序。基础功能已经实现,但现在我正在尝试实现两个不同的命名空间。我希望客户端能够通过点击按钮从一个命名空间(support-chat)切换到另一个命名空间(friends-chat)。
服务端
//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(..)都以相同的方式工作,并捕获其自己命名空间客户端的事件。
非常感谢任何帮助!我觉得命名空间在其“基本用法”文档中被忽视了。