Socket.io在使用命名空间时不发送/接收事件

时间:2022-09-22 19:43:02

I have the following code written in coffeescript that makes use of socket.io and node.js in the server side

我有以下用coffeescript编写的代码,它在服务器端使用socket.io和node.js

Server

io.of("/room").authorization (handshakeData, callback) ->
    #Check if authorized
    callback(null,true)
.on 'connection',  (socket) ->
    console.log "connected!"

    socket.emit 'newMessage', {msg: "Hello!!", type: 1} 

    socket.on 'sendMessage', (data) ->
        @io.sockets.in("/room").emit 'newMessage', {msg: "New Message!!", type: 0} 

Client

socket = io.connect '/'

socket.of("/room")
    .on 'connect_failed',  (reason) ->
    console.log 'unable to connect to namespace', reason
.on 'connect', ->
    console.log 'sucessfully established a connection with the namespace'

socket.on 'newMessage', (message) ->
    console.log "Message received: #{message.msg}"

My problem is that after I started using namespaces the communication between server and client has stopped working. I didn't find any working example similar to this so I might be doing something wrong

我的问题是,在我开始使用命名空间后,服务器和客户端之间的通信已停止工作。我没有找到任何与此相似的工作示例,所以我可能做错了什么

1 个解决方案

#1


5  

Namespaces aren't used on the client like they are used server side. Your client side code should connect directly to the namespace path like this:

客户端上不使用命名空间,就像它们在服务器端使用一样。您的客户端代码应该直接连接到命名空间路径,如下所示:

var socket = io.connect('/namespace');
socket.on('event', function(data) {
  // handle event
});

That being said, namespaces are different than rooms. Namespaces are joined on the client side, while rooms are joined on the server side. Therefore this code won't work:

话虽如此,名称空间与房间不同。命名空间在客户端连接,而房间在服务器端连接。因此,此代码不起作用:

io.sockets.in('/namespace').emit('event', data);

You have to either reference the namespace, or call it from the global io object.

您必须引用命名空间,或从全局io对象中调用它。

var nsp = io.of('/namespace');
nsp.emit('event', data);

// or get the global reference
io.of('/namespace').emit('event', data);

#1


5  

Namespaces aren't used on the client like they are used server side. Your client side code should connect directly to the namespace path like this:

客户端上不使用命名空间,就像它们在服务器端使用一样。您的客户端代码应该直接连接到命名空间路径,如下所示:

var socket = io.connect('/namespace');
socket.on('event', function(data) {
  // handle event
});

That being said, namespaces are different than rooms. Namespaces are joined on the client side, while rooms are joined on the server side. Therefore this code won't work:

话虽如此,名称空间与房间不同。命名空间在客户端连接,而房间在服务器端连接。因此,此代码不起作用:

io.sockets.in('/namespace').emit('event', data);

You have to either reference the namespace, or call it from the global io object.

您必须引用命名空间,或从全局io对象中调用它。

var nsp = io.of('/namespace');
nsp.emit('event', data);

// or get the global reference
io.of('/namespace').emit('event', data);