【发布时间】:2018-06-10 17:47:58
【问题描述】:
我目前正在与 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();
我是否误解了命名空间的用法?我想在 2 个主聊天的名称空间“拆分”之后立即实施房间,以获得支持和朋友。 还是我在服务器端错误地实现了命名空间?我认为 io.on(..)、io.of('/support').on(..) 和 io.of('/friends').on(..) 都以相同的方式工作并抓住他们自己的命名空间客户端的事件。
非常感谢任何帮助!我觉得命名空间在“基本使用”文档中被忽略了。
【问题讨论】:
标签: node.js sockets socket.io namespaces