如何在node.js

时间:2015-04-26 05:49:37

标签: javascript node.js

如何向特定客户端发送消息?是否有可能只向node.js中的特定客户端发送消息?

var net = require('net');

var clients = [];

var server = net.createServer(function (socket) {

   clients.push(socket);

   var message = "message to client";


   //here how to send to a specific client ?   

});

提前谢谢。

1 个答案:

答案 0 :(得分:2)

目前还不完全清楚你要做的是什么,但是你已经在clients数组中保留了一个套接字列表,所以你只需要应用你需要的任何逻辑来选择其中一个套接字然后使用.write()在该套接字上写入一些数据:

var net = require('net');
var clients = [];
var server = net.createServer(function (socket) {
   clients.push(socket);
   var message = "message to client";

   // pick a socket from the array using whatever logic you want and send to it
   clients[0].write(msg);
});