zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    vue-cli快速搭建
    js严格模式下判断数据类型
    js实现本地的图片压缩上传预览
    web端实现图片放大切换显示预览
    swiper.js在隐藏/显示切换时,轮播出现bug的解决办法
    Zepto.js实现fadeIn,fadeOut功能
    ms
    redis 解决秒杀
    单下滑线 事务 锁
    极验
  • 原文地址:https://www.cnblogs.com/sumuzhe/p/7466945.html
Copyright © 2011-2022 走看看