2016-02-12 16 views
0

我在套接字中用於perl和POE編程,我正在研究如何將node.js用於不基於Web的應用程序服務器。我從編寫網頁用戶界面獲得JavaScript知識。如何將數據發送到使用net.createServer()連接事件創建的特定套接字?

我一直在使用網絡模塊,並已成功地從多個客戶端同時連接到它。

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

所以我遇到的問題是,如果我創造了另一種功能,需要將數據發送到特定的客戶端,而不是所有的人的廣播,我無法弄清楚如何做到這一點。

我已經在這裏和谷歌做了大量的搜索。很多簡單的tcp服務器和回顯服務器的例子給一個客戶端,但沒有多個客戶端。

我想這樣做沒有socket.io因爲並非所有的客戶端都將基於Web。

任何幫助,將不勝感激,

ž

回答

1

你必須自己對它們以某種方式保存,不管是簡單地增加一個數組或增加鍵安裝在例如一些獨特標識符的對象。

下面是使用對象:

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

然後你就可以找到它的綽號分配一個特定的插座。

+0

非常感謝! – Zanderfax

0

這是示例工作代碼。希望這會對其他人有用!

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); 
}); 
相關問題