Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io not emitting/receiving events while using namespaces

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

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

like image 287
Gorka Lauzirika Avatar asked May 12 '26 23:05

Gorka Lauzirika


1 Answers

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.

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

// or get the global reference
io.of('/namespace').emit('event', data);
like image 179
hexacyanide Avatar answered May 15 '26 12:05

hexacyanide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!