如何将数据发送到使用net.createServer()连接事件创建的特定套接字?

时间:2016-02-12 16:44:32

标签: javascript node.js sockets

在套接字方面,我习惯于perl和POE编程,我正在考虑将node.js用于非基于Web的应用服务器。我从编写网页用户界面获得JavaScript知识。

我一直在使用网络模块,并且已经成功地同时从多个客户端连接到它。

var net = require('net');
var port = 63146;
var socketNum = 0;

var adminServer = net.createServer(function(socket){
     //add connection count
     socketNum++;
     socket.nickname = "Con# " + socketNum;
     var clientName = socket.nickname;

     console.log(clientName + "connected from " + socket.remoteAddress);
     socket.write("You have been given the client name of " + clientName);
 });

adminServer.listen(port, function() {
    console.log("Server listening at" + port);
});

所以我遇到的问题是,如果我创建了另一个需要将数据发送到特定客户端的功能,而不是向所有客户端发送广播,我无法弄清楚如何做到这一点。

我在这里和Google进行了广泛的搜索。很多简单的tcp服务器和echo服务器到单个客户端的例子,但没有多个客户端的例子。

我试图在没有socket.io的情况下这样做,因为并非所有的客户都是基于网络的。

任何帮助将不胜感激,

ž

2 个答案:

答案 0 :(得分:3)

你必须以某种方式自己存储它们,无论是简单地添加到数组还是添加到以某个唯一标识符键入的对象为例。

这是使用对象:

var net = require('net');
var port = 63146;
var socketNum = 0;
var sockets = Object.create(null);

var adminServer = net.createServer(function(socket){
     //add connection count
     socketNum++;
     socket.nickname = "Con# " + socketNum;
     var clientName = socket.nickname;

     sockets[clientName] = socket;
     socket.on('close', function() {
       delete sockets[clientName];
     });

     console.log(clientName + " connected from " + socket.remoteAddress);
     socket.write("You have been given the client name of " + clientName);
 });

adminServer.listen(port, function() {
    console.log("Server listening at" + port);
});

然后,您可以通过其指定的昵称找到特定套接字。

答案 1 :(得分:1)

以下是示例工作代码。希望这对其他人有用!

var net = require('net');
var port = 63146;
var conSeen = Object.create(null);
var socketNum = 0;

var adminServer = net.createServer(function(socket){
     //add connection count
     socketNum++;
     socket.nickname = "Con" + socketNum;
     var clientName = socket.nickname;
     //console.log(socket);

 conSeen[clientName] = socket;

 socket.on('close', function() {
   delete sockets[clientName];
 });

 console.log(clientName + " has connected from " + socket.remoteAddress);
 socket.write("You have been given the client name of " + clientName + "\r\n");
 socket.on('data', function(inputSeen) {
          var clientName = socket.nickname;
          var input = inputSeen.toString('utf8'); 
          input = input.replace(/(\r\n|\n|\r)/gm,"");
          console.log("Saw : " + input + " from " + clientName + "\r\n");
          if (input === 'sendTest') {
            conSeen[clientName].write('test 123\r\n');
          }
     });

});



adminServer.listen(port, function() {
    console.log("Server listening on " + port);
});