连接插座io房间连接 [英] Joining socket io room on connect
问题描述
我正在尝试让登录用户加入连接上的某个socket.io房间。
根据我在网上发现的任何例子,我似乎已经从客户端发出一些动作,以便能够加入一些房间。
类似于:
I am trying to make a logged in user to join a certain socket.io room on connect. According to any examples I found on the net I seem to have emit some action from client to be able to join some room. Something like:
socket.on('connect', function() {
socket.emit('join', 'room1');
});
Server.js:
Server.js:
io.sockets.on('connection', function(socket) {
socket.on('join', function(room) {
socket.join(room);
});
});
根据大多数教程,它应该有效。
And according to most tutorials it should work.
我的想法是:
socket.on('connect', function() {
socket.join('room1');
});
但它似乎不起作用,因为我从服务器发出的消息不会被客户端捕获。任何想法,我做错了什么?一般情况下是否可能?
But It does not seem to work as whatever msg I emit from server are not caught on client. Any idea, what am I doing wrong? Is it possible in general?
推荐答案
没有 .join()
客户端方法。房间纯粹是服务器端构造,客户端对它们一无所知。
There is no .join()
method on the client side. Rooms are purely a server-side construct and the client knows nothing about them.
您的第一个代码块是理想的处理方式。您向服务器发送一条设计消息,要求它将套接字加入房间,并在服务器端执行 .join()
。
Your first block of code is the desired way to do things. You send the server a message of your design asking it to join the socket to a room and the .join()
is executed on the server side.
这篇关于连接插座io房间连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!