如何在使用node.js时将数据发送到指定的连接

我正在使用node.js构build一个TCP服务器,就像doc中的例子。 服务器build立持久连接并处理客户端请求。 但是我也需要发送数据到任何指定的连接,这意味着这个动作不是由客户端驱动的。 怎么做?

您的服务器可以通过在服务器上添加“连接”事件并在stream上删除“closures”事件来维护活动连接的数据结构。 然后,您可以从该数据结构中select所需的连接,并随时向其写入数据。

下面是一个简单的时间服务器示例,它每秒将当前时间发送给所有连接的客户端:

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);