wxConnect，基于connect实现对微信消息事件处理的简单封装

@param config
@returns {*|exports}
421901
function wxConnect(config) {
  var app = connect();
  app.use(bodyParser.text({type: 'text/xml'})); // 获取请求体内容
  app.use(signature(config)); // 验证接受来自微信端发送的消息真实性
  app.use(message); // 解析微信端发送的XML消息

  // 分派消息处理
  app.use(function(req, res, next) {
    // 分派文本消息处理
    if (req.message.msgType == 'text' && app.text) {
      return app.text.call(app, req, res, next);
    }

    // 分派地理位置上报事件处理
    if (req.message.msgType == 'event' && req.message.event == 'LOCATION' && app.location) {
      return app.location.call(app, req, res, next);
    }

    // 分派自定义菜单点击事件处理
    if (req.message.msgType == 'event' && req.message.event == 'CLICK' && app.menu) {
      return app.menu.call(app, req, res, next);
    }

    // 分派用户关注事件处理
    if (req.message.msgType == 'event' && req.message.event == 'subscribe' && app.subscribe) {
      return app.subscribe.call(app, req, res, next);
    }

    // 分派用户取消关注事件处理
    if (req.message.msgType == 'event' && req.message.event == 'unsubscribe' && app.unsubscribe) {
      return app.unsubscribe.call(app, req, res, next);
    }
  });

  // 默认消息处理，在消息/事件没有被分派时调用
  app.use(function(req, res, next) {
    res.text(util.inspect(req.message));
  });

  // 错误处理
  app.use(function(error, req, res, next) {
    console.log(error);
    res.text('' + error);
  });

  return app;
}
1008690
function connStr(conn) {
  var conf = mergeDefaults(conn);
  var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
    + (conf.port ? ':' + conf.port : '') + '/' + conf.database;
  return connString;
}
448342
protected function _connection(array $config)
    {
        $redis = new \Redis;
        $host = empty($config['host']) ? self::DEFAULT_HOST : $config['host'];
        $port = empty($config['port']) ? self::DEFAULT_PORT : $config['port'];
        $timeout = empty($config['timeout']) ? self::DEFAULT_TIMEOUT : $config['timeout'];
        $connect = empty($config['persistent']) ? 'connect' : 'pconnect';
        $redis->$connect($host, $port, $timeout);
        return $redis;
    }
1107672
public static EventLoopGroup getServerIoEventLoopGroup(ServerTransportConfig config) {
        String type = config.getProtocolType();
        EventLoopGroup ioGroup = serverIoGroups.get(type);
        if (ioGroup == null) {
            synchronized (NettyHelper.class) {
                ioGroup = serverIoGroups.get(config.getProtocolType());
                if (ioGroup == null) {
                    int ioThreads = config.getIoThreads();
                    ioThreads = ioThreads <= 0 ? Math.max(8, SystemInfo.getCpuCores() + 1) : ioThreads;
                    NamedThreadFactory threadName =
                            new NamedThreadFactory("SEV-IO-" + config.getPort(), config.isDaemon());
                    ioGroup = config.isUseEpoll() ?
                        new EpollEventLoopGroup(ioThreads, threadName) :
                        new NioEventLoopGroup(ioThreads, threadName);
                    serverIoGroups.put(type, ioGroup);
                    refCounter.putIfAbsent(ioGroup, new AtomicInteger(0));
                }
            }
        }
        refCounter.get(ioGroup).incrementAndGet();
        return ioGroup;
    }
24342
function Socket(config) {
    var host = config.host || '127.0.0.1',
        port = config.port || 8880,
        maxsize = config.maxsize || MAXSIZE,
        encoding = config.encoding || 'utf8',
        callback = config.callback,
        broadcast = config.broadcast || true;

    var clientList = [];

    var server = net.createServer(function(socket) {
        utils.log('[socket connected successfully]: ', socket.remoteAddress + ':' + socket.remotePort);
        
        clientList.push(socket);

        socket.setEncoding(encoding);

        socket.on('lookup', function() {
            utils.log('[create socket]');
        });

        socket.on('connect', function(sock) {
            utils.log('[socket connected successfully]: ', sock.remoteAddress + ':' + sock.remotePort);
        });

        socket.on('data', function(data) {
            //data = socket.remoteAddress + '|' + socket.remotePort + ':\n' + data;
            //utils.log('socket get data:\n', data);

            callback && callback(data, socket);

            // broadcast && socket.write(data, function() {
            //     utils.log('[socket broadcast one data]');
            // });

            if(broadcast){
                utils.log('[socket broadcast one data]');
                for(var i in clientList){
                    var sock = clientList[i];
                    //不广播给自己
                    (sock !== socket) && (function(sock, data){
                        var dataFrom = socket.remoteAddress + ':' + socket.remotePort;// + ':\n' + data
                        sock.write(dataFrom + ':\n' + data, function() {
                            var dataTo = sock.remoteAddress + ':' + sock.remotePort;
                            utils.log('[' + dataFrom + ' send a message to ' + dataTo + ']:\n', data);
                        });
                    })(sock, data);
                }
            }
            //socket.end();
        });

        socket.on('end', function() {
            console.log('end');
        });

        socket.on('drain', function() {
            console.log('drain');
        });

        socket.on('error', function(err) {
            console.log('[socket error]: ', err)
        });

        socket.on('close', function() {
            clientList.splice(clientList.indexOf(socket), 1);
            socket.destroy();
            console.log('[client closed]');

        });

        socket.write('hello\r\n');
        //socket.pipe(socket);
        //console.log(socket);
    })
    .listen(port, host, function() { //'listening' listener
        console.log('server bound: ', host, ':', port);
    })
    .on('connection', function(){
        console.log('[new socket connection], count: ', clientList.length);
    })
    .on('error', function(err){
        console.log('[server error]:', err);
        if (err.code == 'EADDRINUSE') {
            console.log('Address in use, retrying...');
            setTimeout(function() {
                server.close();
                server.listen(PORT, HOST);
            }, 1000);
        }
    })
    .on('close', function(){
        console.log('[server closed]');
    })
}
42498
public function connection($config = null, $forceConnect = false)
    {

        if ($this->connection && !$forceConnect) {
            return $this->connection;
        }

        !isset($config) || $this->config($config);

        $ref = new \ReflectionClass($this->getHandler());

        try {
            /** @var \PDO $connection */
            $this->connection = $ref->newInstanceArgs([
                $this->getConnectionString(),
                $this->getUser(),
                $this->getPassword(),
                $this->getHandlerOptions()
            ]);
        } catch (\PDOException $e) {
            throw new DatabaseException($e->getMessage());
        }

        return $this->connection;
    }
734652
protected function getNewMySqlConnection(array $config, string $connection = null)
    {
        if ($connection && isset($config[$connection])) {
            $config = array_merge($config, $config[$connection]);
        }

        return ConnectorFactory::make(FW::version())->connect($config);
    }
847753
function getPort(config, skyPagesConfig) {
  return new Promise((resolve, reject) => {
    const configPort = skyPagesConfig &&
      skyPagesConfig.skyux &&
      skyPagesConfig.skyux.app &&
      skyPagesConfig.skyux.app.port;

    if (configPort) {
      resolve(configPort);
    } else if (config.devServer && config.devServer.port) {
      resolve(config.devServer.port);
    } else {
      portfinder.getPortPromise()
        .then(port => resolve(port))
        .catch(err => reject(err));
    }
  });
}
529391
public static RedissonRxClient createRx(Config config) {
        RedissonRx react = new RedissonRx(config);
        if (config.isReferenceEnabled()) {
            react.enableRedissonReferenceSupport();
        }
        return react;
    }
562757
private function createConnection($config): Connection
    {
        if (is_string($config)) {
            $config = ['url' => $config];
        }

        return DriverManager::getConnection($config, $this->configuration, $this->eventManager);
    }
860794
function connect(connector){
    return connector.connect().then(function() {
    	// Set time
    	date = new Date();

        // If we are here, we are connected
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Connected to: '+ connector.endpoint.host +'</p>');
    	
        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to errors</p>');

        // Subscribe to errors channel
        nem.com.websockets.subscribe.errors(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received error</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to new blocks</p>');

        // Subscribe to new blocks channel
        nem.com.websockets.subscribe.chain.blocks(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received a new block</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to recent transactions</p>');

        // Subscribe to recent transactions channel
        nem.com.websockets.subscribe.account.transactions.recent(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received recent transactions</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to account data of '+ connector.address +'</p>');

        // Subscribe to account data channel
        nem.com.websockets.subscribe.account.data(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received account data</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to unconfirmed transactions of '+ connector.address +'</p>');

        // Subscribe to unconfirmed transactions channel
        nem.com.websockets.subscribe.account.transactions.unconfirmed(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received unconfirmed transaction</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to confirmed transactions of '+ connector.address +'</p>');

        // Subscribe to confirmed transactions channel
        nem.com.websockets.subscribe.account.transactions.confirmed(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received confirmed transaction</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });
        
        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Requesting account data of '+ connector.address +'</p>');

        // Request account data
        nem.com.websockets.requests.account.data(connector);

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Requesting recent transactions of '+ connector.address +'</p>');
        
        // Request recent transactions
        nem.com.websockets.requests.account.transactions.recent(connector);

    }, function(err) {
        // Set time
        date = new Date();
        // Show event
        $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> An error occured</p>');
        // Show data
        $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(err) +'</pre>');
        // Try to reconnect
        reconnect();
    });
}
497441
function Server(config) {
  utils.verbose(config.verbose)

  this._wsStarted = false
  this._wsStopped = false

  this._wsConfig = config
  this._wsServer = new websocket.server()

  this._onRequest = config.onRequest

  this._wsServer.addListener("request", this._onRequest)
  this._wsServer.addListener("connect", onConnect)
}
1113033
protected ConnectorController createConnectorController(ServletConfig config)
	{
		ConnectorController connectorController = new ConnectorController();

		connectorController
				.setCommandExecutorFactory(createCommandExecutorFactory(config));
		connectorController.setFsServiceFactory(createServiceFactory(config));

		return connectorController;
	}
122131
public static Xml exports(LaunchableConfig config)
    {
        Check.notNull(config);

        final Xml node = new Xml(NODE_LAUNCHABLE);
        node.writeString(ATT_MEDIA, config.getMedia());
        node.writeInteger(ATT_DELAY, config.getDelay());
        node.writeInteger(ATT_OFFSET_X, config.getOffsetX());
        node.writeInteger(ATT_OFFSET_Y, config.getOffsetY());
        node.add(ForceConfig.exports(config.getVector()));

        return node;
    }
145228
public function connect(array $config)
    {
        $client = $this->getClient($config);

        return $this->getAdapter($client, $config);
    }
622451
public OperationFuture<ServerMetadata> importServer(ImportServerConfig config) {
        BaseServerResponse response = client.importServer(
            serverConverter.buildImportServerRequest(
                config,
                config.getCustomFields().isEmpty() ?
                    null :
                    client.getCustomFields()
            )
        );

        return postProcessBuildServerResponse(response, config);
    }
858890
public static List<Connector> createDefaultConnectors(Map<String, Object> properties) {
        List<Connector> connectors = Lists.newArrayList();
        Map<String, Map<String, String>> propertiesMap = Maps.newLinkedHashMap();
        for (String key : properties.keySet()) {
            if (key.startsWith(Connector.CONNECTOR_CONF_PREFIX)) {
                String oKey = key;
                key = key.substring(Connector.CONNECTOR_CONF_PREFIX.length());
                int index = key.indexOf(".");
                if (index == -1) {
                    throw new ConfigErrorException("connector configure error, format connector.{connectorName}.{property}");
                }
                String name = key.substring(0, index);
                Map<String, String> pr = propertiesMap.get(name);
                if (pr == null) {
                    pr = Maps.newLinkedHashMap();
                    propertiesMap.put(name, pr);
                    pr.put("name", name);
                }
                pr.put(key.substring(index + 1), String.valueOf(properties.get(oKey)));
            }
        }

        connectors.addAll(propertiesMap.values().stream().map(Connector::createDefault).collect(Collectors.toList()));
        return connectors;
    }