如何向node.js中的特定客户端发送消息 [英] How do I send message to specific client in node.js

查看:309
本文介绍了如何向node.js中的特定客户端发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向特定客户端发送消息?我是否可以仅向node.js中的特定客户端发送消息?

How can I send message to specific client ?,is it possible that I can send only message to a specific client in 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 ?   

});

提前谢谢。

推荐答案

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

It's not entirely clear exactly what you're trying to do, but you are already keeping a list of sockets in the clients array so you just need to apply whatever logic fits your need to select one of those sockets and then use .write() to write some data on that socket:

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

这篇关于如何向node.js中的特定客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆