Node.js telnet聊天服务器

时间:2015-11-04 12:35:14

标签: javascript node.js asynchronous telnet

我正在尝试使用node.js创建一个telnet聊天服务器

当我打开多个终端并输入文本时,

什么都没有出现。 即文本不会传输到另一个终端

我打开几个终端并输入

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

1 个答案:

答案 0 :(得分: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);