苏幕遮零

好好学习,天天向上!

导航

Node.js 一个简单的TCP Sever

代码如下所示:

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

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

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

channel.on('leave', function (id) {
    channel.removeListener('broadcast', this.subscriptions[id]);
    channel.emit('broadcast', id, id + " has left the chat.\n");
});

channel.on('shutdown', function () {
    channel.emit('broadcast', '', "Chat has shut down.\n");
    channel.removeAllListeners('broadcast');
});
channel.setMaxListeners(50);

var server = net.createServer(function (client) {
    var id = client.remoteAddress + ':' + client.remotePort;
      channel.emit('join', id, client);
    client.on('data', function (data) {
        data = data.toString();
        if (data == "shutdown\r\n") {   // 在win10中不匹配,因为win10中telnet的data只会对应一个字符
            channel.emit('shutdown');
        }
        channel.emit('broadcast', id, data);
    });
    client.on('close', function () {
        channel.emit('leave', id);
    });
});
server.listen(8888);

 

posted on 2017-09-02 16:09  苏幕遮零  阅读(155)  评论(0编辑  收藏  举报