io.of('namespace').emit('event', message) not working with namespace in socket.io

前端 未结 1 1281
情歌与酒
情歌与酒 2021-01-19 12:04

I have an app like this following:

io.of(\'/hello\').on(\'connection\', function(socket) {
    socket.emit(\'world\', {});
});

app.post(\'/\', function *(ne         


        
1条回答
  •  伪装坚强ぢ
    2021-01-19 12:56

    Your code is more or less fine, but you are on different namespaces.

    io.sockets.emit() broadcasts to everybody currently connected to your server via socket. That's the reason it works. Technically it's because that's a 'shortcut' for io.of('').emit() ('' being the namespace).

    Assuming you're going to use the /hello namespace, this is what you have to do on your client:

    var socket = io.connect('http://localhost:3000/hello'); // your namespace is /hello
    

    on the server you first have to listen for connections on that namespace:

    io.of('/hello').on('connection', function(socket) {
      socket.emit('world', { a: 'hi world' });
    });
    

    then:

    io.of('/hello').emit('something');
    

    You may want to look at these: socket.io: How to use and socket.io rooms on GitHub

    ### UPDATE ###

    I conducted a little test:

    client:

    $('document').ready(function() {
      var socket = io.connect("localhost:3000/hello");
    
      socket.on('hello', function() {
        console.log('hello received');
      });
    
      var data = {};
      data.title = "title";
      data.message = "message";
    
      setTimeout(function() {
        $.ajax({
          type: 'POST',
          data: JSON.stringify(data),
          contentType: 'application/json',
          url: 'http://localhost:3000/hello',
          success: function(data) {
            console.log('success');
            console.log(JSON.stringify(data));
          }
        });
       }, 2000);
    });
    

    server:

    io.of('/hello').on('connection', function() {
      console.log("client connected");
    });
    
    app.post('/hello', function(req, res) {
      io.of('/hello').emit('hello');
    });
    

    ... and it worked. I copied the jquery-ajax code from here.

    0 讨论(0)
提交回复
热议问题