实时更新机制:用户写入 - > php将其保存在mysql db-> php将信息发送到nodejs-> nodejs发送更改所有订户 - >其他订户可以实时注意到它。

socket.io服务器运行良好并在端口8080上运行。我有在端口80上运行的节点HTTP服务器。如何在HTTP服务器上获取触发消息并将消息发送到所有socket.io客户端?

var io = require('socket.io').listen(8080);

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Message Broadcast\n');
  console.log("Message Sent");

  //DOES NOT SEEM TO WORK, error
  io.broadcast("Messages");

  //No error but no messages
  io.emit("Message");

}).listen(80, "0.0.0.0");


/**
Other socket.io code which works well..
....
有帮助吗?

解决方案

在socket.io 0.7中,您应该使用以下内容,而不是在没有特定套接字参考的情况下发送到所有连接的插座:

io.sockets.send("Messages")

请注意,这与 broadcast 因为那会发送到所有插座 除了 启动连接的套接字 - 当然,您需要发送插座参考,这就是为什么您当前代码不足的原因。

引用Wiki页面: socket.io/wiki

如果您想向所有人发送消息,您可以参考 io.sockets:

io.sockets.send('message');

io.sockets.emit('event');

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top