2015-11-04 60 views
0

我試圖讓使用Node.js的,當我打開多個終端,並輸入文字Node.js的遠程登錄聊天服務器

沒有出現一個telnet聊天服務器。 即文本不會傳輸到其他終端

我打開serveral的終端,並進入

telnet 127.0.0.1 8888 

然後開始打字,但

var events = require('events'); 
var net = require('net'); 

var channel = new events.EventEmitter(); 
channel.clients = {}; 
channel.subscriptions = {}; 

channel.on('join', function(id, client) { 
    console.log("join"); 
    this.clients[id] = client; 
    this.subscriptions[id] = function(senderId, message) { 
     if (id != senderId) { 
      this.clients[id].write(message); 
     } 
    } 
    this.on('broadcast', this.subscriptions[id]); 
}); 

var server = net.createServer(function(client) { 
    console.log("createServer"); 
    var id = client.remoteAddress + ':' + client.remotePort; 
    client.on('connect', function() { 
     console.log("connect"); 
     channel.emit('join', id, client); 
    }); 
    client.on('data', function(data) { 
     console.log("data"); 
     data = data.toString(); 
     channel.emit('broadcast', id, data); 
    }); 
}); 

server.listen(8888); 

回答

0

我已經簡化似乎沒有(那種)代碼展示如何發送郵件給用戶:

var events = require('events'); 
var net = require('net'); 

clients = []; 

function randomInt (low, high) { 
    return Math.floor(Math.random() * (high - low) + low); 
} 
function generateId(length) { 
    var output = ""; 
    for(var i = 0;i<length;i++) { 
     output += randomInt(0,9); 
    } 
    return output; 
} 

function sendToAll(data,sender) { 
    console.log(clients.length); 
    var size = clients.length; 
    for(i=0;i<size;i++) { 
     if(sender.unique_id != clients[i].unique_id) { 
      clients[i].write(data); 
     } 
    } 
} 

var server = net.createServer(function(client) { 
    console.log("New client: " + client.remoteAddress); 
    client.write("Welcome!\r\n"); 
    client.unique_id = generateId(10); 
    clients.push(client); 

    client.on('data', function(data) { 
     data = data.toString(); 
     console.log(data); 
     sendToAll(data,client); 
    }); 
}); 

server.listen(8888);