• 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.
    ");
    });
    
    channel.on('shutdown', function () {
        channel.emit('broadcast', '', "Chat has shut down.
    ");
        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
    ") {   // 在win10中不匹配,因为win10中telnet的data只会对应一个字符
                channel.emit('shutdown');
            }
            channel.emit('broadcast', id, data);
        });
        client.on('close', function () {
            channel.emit('leave', id);
        });
    });
    server.listen(8888);
  • 相关阅读:
    Linux下安装vmtools的语句
    [WP]BugkuCtf
    Linux文件属性及权限
    学习pwn的前提工作及部分解决方案
    windows环境下MySQL mysql-5.7.17-winx64 (社区服务版,community server)安装教程
    ubuntu14.04 LTS 更新国内网易163源
    session cookie
    java collection map
    重温 总结 maven几个重要概念
    java通信
  • 原文地址:https://www.cnblogs.com/sumuzhe/p/7466945.html
Copyright © 2020-2023  润新知