io.of('namespace').emit('event',message)在socket.io中不使用namespace

Ari*_*vil 3 node.js socket.io

我有一个像这样的应用程序:

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

app.post('/', function *(next) {
    console.log("At here......");
    var pushMessage = (yield parse.json(this));
    console.log(pushMessage);
    if(flag !== 0) {
//        io.of('/hello/').emit('world', pushMessage);
        io.sockets.emit('world', pushMessage);
    } else {
        console.log("Do Nothing");
    }
});
Run Code Online (Sandbox Code Playgroud)

它收到一个http请求并发出一个事件.当我使用io.sockets.emit时它运行良好,但是当我用'io.of('hello')指定一个命名空间时,发出'它'不起作用,为什么?

我的客户端是这样的:

var socket = io.connect('http://localhost:3000', {
  'reconnection delay': 100,
  'reconnection limit': 100,
  'max reconnection attempts': 10
});
//server side use io.sockets.emit
socket.on('world', function(data) {
  alert(data.a);
});

//if server side use io.of('/hello/').emit
//socket.of('/hello/').on('world', function(data) {
//  alert(data.a);
//});
Run Code Online (Sandbox Code Playgroud)

小智 10

您的代码或多或少都很好,但您使用的是不同的命名空间.

io.sockets.emit()通过套接字向当前连接到服务器的每个人广播.这就是它起作用的原因.从技术上讲,这是因为它是io.of('').emit()(''作为命名空间)的"捷径" .

假设您要使用/hello命名空间,这是您必须在客户端上执行的操作:

var socket = io.connect('http://localhost:3000/hello'); // your namespace is /hello
Run Code Online (Sandbox Code Playgroud)

在服务器上,您首先必须侦听该命名空间上的连接:

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

然后:

io.of('/hello').emit('something');
Run Code Online (Sandbox Code Playgroud)

你可能想看看这些:socket.io:如何在GitHub上使用socket.io房间

###更新###

我做了一点测试:

客户:

$('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);
});
Run Code Online (Sandbox Code Playgroud)

服务器:

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

app.post('/hello', function(req, res) {
  io.of('/hello').emit('hello');
});
Run Code Online (Sandbox Code Playgroud)

......而且它奏效了.我从这里复制了jquery-ajax代码.