如何在使用node.js时将数据发送到指定连接
问题描述:
我正在使用node.js构建TCP服务器,就像doc中的示例一样。服务器建立持久连接并处理客户端请求。但是我也需要将数据发送到任何指定的连接,这意味着此操作不是由客户端驱动的。怎么做?如何在使用node.js时将数据发送到指定连接
答
您的服务器可以通过在服务器上添加“连接”事件并删除流上的“关闭”事件来维护活动连接的数据结构。然后,您可以从该数据结构中选择所需的连接,并在需要时将数据写入该连接。
这里是一个将当前时间到所有连接的客户端每秒一时间服务器的一个简单的例子:这只是不是典型的服务器成语
var net = require('net')
, clients = {}; // Contains all active clients at any time.
net.createServer().on('connection', function(sock) {
clients[sock.fd] = sock; // Add the client, keyed by fd.
sock.on('close', function() {
delete clients[sock.fd]; // Remove the client.
});
}).listen(5555, 'localhost');
setInterval(function() { // Write the time to all clients every second.
var i, sock;
for (i in clients) {
sock = clients[i];
if (sock.writable) { // In case it closed while we are iterating.
sock.write(new Date().toString() + "\n");
}
}
}, 1000);
。服务器坐在等待来自客户端的消息,当他们到达时就处理这些消息,然后等待更多消息。如果服务器向客户端发送消息而客户端没有向服务器发送消息,则不能保证客户端甚至正在侦听来自服务器的消息。 – 2011-06-02 04:09:14
@Matt Ball:HTTP服务器就是如此,但一般的TCP客户端/服务器应用程序可以运行他们想要的任何协议,包括服务器向客户端发送“未经请求”消息的服务器...... – maerics 2011-06-17 01:24:53