Swoole Websocket Server
17977
public function websocket()
    {
        $this->writeln('Starting swoole websocket server...');

        $ws = new WebsocketServer(
            $this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT
        );

        $ws->on(
            'open', function ($ws, $request) {
                $this->writeln('client-Connect.');
            }
        );

        $ws->on(
            'message', function ($ws, $frame) {
                $jsonData = JsonHelper::decode($frame->data);
                if (isset($jsonData['handler'])) {
                    $jsonData['swoole_frame'] = $frame;
                    $handlerClass = $jsonData['handler'];
                    try {
                        $ws->push(
                            $frame->fd,
                            Lb::app()->dispatchJob($handlerClass, $jsonData)
                        );
                    } catch (\Throwable $e) {
                        $ws->push(
                            $frame->fd,
                            'Exception:' . $e->getTraceAsString()
                        );
                    }
                } else {
                    $ws->push(
                        $frame->fd,
                        'Handler not exists'
                    );
                }
            }
        );

        $ws->on(
            'close', function ($ws, $fd) {
                $this->writeln('client-closed');
            }
        );

        $ws->start();
    }
1092779
public function onStart(swoole_server $server)
    {
        if (version_compare(SWOOLE_VERSION, '1.9.5', '<')) {
            file_put_contents($this->pidFile, $server->master_pid);
            $this->pid = $server->master_pid;
        }

        process_rename($this->name . ' master');

        $this->output->writeln(sprintf("Listen: <info>%s://%s:%s</info>", $this->getScheme(), $this->getHost(), $this->getPort()));
        foreach ($this->listens as $listen) {
            $this->output->writeln(sprintf(" <info> ></info> Listen: <info>%s://%s:%s</info>", $listen->getScheme(), $listen->getHost(), $listen->getPort()));
        }

        $this->output->writeln(sprintf('PID file: <info>%s</info>, PID: <info>%s</info>', $this->pidFile, $server->master_pid));
        $this->output->writeln(sprintf('Server Master[<info>%s</info>] is started', $server->master_pid), OutputInterface::VERBOSITY_DEBUG);
    }
281936
private function startWsServer()
    {
        if (! $this->serverInstance instanceof RatchetWsServer) {
            throw new \Exception("{$this->class} must be an instance of ".RatchetWsServer::class." to create a WebSocket server");
        }

        $this->bootWithBlacklist();

        return $this->bootWebSocketServer();
    }
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
1151251
function Federate(object, target, wspool, options) {
  events.EventEmitter.call(this);
  this.object = object;
  this.target = target;
  this.reconnecting = false;
  this.channelpool = wspool;
  this.state = {};
  this._options(options);
  this.queue = [];
  this._attachWs(false);
}
1374250
private function initWebsocketServer()
    {
        $websocketBind = $this->sandstoneApplication['sandstone.websocket.server']['bind'];
        $websocketPort = $this->sandstoneApplication['sandstone.websocket.server']['port'];

        $socket = new ReactSocketServer("$websocketBind:$websocketPort", $this->loop);

        new IoServer(
            new HttpServer(
                new WsServer(
                    new ServerProtocol(
                        new WebsocketApplication(
                            $this->sandstoneApplication
                        )
                    )
                )
            ),
            $socket
        );
    }
875718
protected function bindWebsocket()
    {
        $this->app->singleton(Websocket::class, function (Container $app) {
            return new Websocket($app->make(RoomContract::class), new Pipeline($app));
        });

        $this->app->alias(Websocket::class, 'swoole.websocket');
    }
639257
protected function start()
    {
        if ($this->isRunning($this->getCurrentPid())) {
            $this->error('Failed! swoole_http_server process is already running.');

            return;
        }

        $host = Arr::get($this->config, 'server.host');
        $port = Arr::get($this->config, 'server.port');
        $hotReloadEnabled = Arr::get($this->config, 'hot_reload.enabled');
        $accessLogEnabled = Arr::get($this->config, 'server.access_log');

        $this->info('Starting swoole http server...');
        $this->info("Swoole http server started: <http://{$host}:{$port}>");
        if ($this->isDaemon()) {
            $this->info(
                '> (You can run this command to ensure the ' .
                'swoole_http_server process is running: ps aux|grep "swoole")'
            );
        }

        $manager = $this->laravel->make(Manager::class);
        $server = $this->laravel->make(Server::class);

        if ($accessLogEnabled) {
            $this->registerAccessLog();
        }

        if ($hotReloadEnabled) {
            $manager->addProcess($this->getHotReloadProcess($server));
        }

        $manager->run();
    }
458482
def queue_poll(self, sleep_t=0.5):
        
        connection_alive = True

        while self.running:
            if self.ws:
                def logger_and_close(msg):
                    self.log.error('Websocket exception', exc_info=True)
                    if not self.running:
                        # Tear down has been invoked
                        # Prepare to exit the program
                        connection_alive = False  # noqa: F841
                    else:
                        if not self.number_try_connection:
                            # Stop everything.
                            self.teardown()
                            self._display_ws_warning()

                with catch(websocket.WebSocketException, logger_and_close):
                    result = self.ws.recv()
                    self.queue.put(result)

            if connection_alive:
                time.sleep(sleep_t)
670851
function EmulatedWebSocketServerFactory() {
        this.createServer = function (connectCallback) {
            var server = {
                _connect: function (socket) {
                    var conn = {
                        _client: socket,
                        _listeners: { "text": [], "close": [] },
                        on: function (type, listener) {
                            conn._listeners[type].push(listener);
                        },
                        _fire: function (type, args) {
                            conn._listeners[type].forEach(function (listener) {
                                listener.apply(null, args);
                            });
                        },

                        _text: function (msg) {
                            conn._fire("text", [msg]);
                        },
                        sendText: function (msg) {
                            setTimeout(function () {
                                conn._client._text(msg);
                            }, 0);
                        },
                        close: function (code, reason) {
                            setTimeout(function () {
                                conn._client._disconnect(code, reason);
                            }, 0);
                        },
                        _disconnect: function (code, reason) {
                            conn._fire("close", [code, reason]);
                        }
                    };
                    connectCallback(conn);
                    return conn;
                },
                listen: function (port) {
                    EmulatedWebSocketServerFactory.listeners[port] = this;
                    return this;
                }
            }
            return server;
        }
    }
1197627
async def running(self):
        """"""
        try:
            async with self._session.ws_connect(self._url) as ws:
                self.state = STATE_RUNNING
                async for msg in ws:
                    if msg.type == aiohttp.WSMsgType.TEXT:
                        ensure_future(self._async_callback(
                            json.loads(msg.data)))
                        _LOGGER.debug('Websocket data: %s', msg.data)
                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        break
                    elif msg.type == aiohttp.WSMsgType.ERROR:
                        break
        except aiohttp.ClientConnectorError:
            if self.state != STATE_STOPPED:
                self.retry()
        except Exception as err:
            _LOGGER.error('Unexpected error %s', err)
            if self.state != STATE_STOPPED:
                self.retry()
        else:
            if self.state != STATE_STOPPED:
                self.retry()
27101
function WSMuxChannel(id, mux) {
  EventEmitter.call(this);
  this.id = id;
  this.mux = mux;
  this.closed = false;
  this.url = this.mux.url;

  // websocket-stream relies on this method
  this.__defineGetter__('readyState', function() {
    return this.mux._readyState();
  });

  // hooks for websocket-stream
  var _this = this;
  this.on('open', function() {
    _this.onopen && _this.onopen.apply(_this, arguments);
  });

  this.on('close', function() {
    _this.onclose && _this.onclose.apply(_this, arguments);
  });

  this.on('error', function() {
    _this.onerror && _this.onerror.apply(_this, arguments);
  });

  this.on('message', function() {
    arguments[0] = {data: arguments[0]}
    _this.onmessage && _this.onmessage.apply(_this, arguments);
  });
}
1354544
function Client(key, options, GenericSocket) {
	var self = this,
		genericSocket = GenericSocket || undefined;
	
	self.connection = IrcSocket(options, genericSocket);
	self.options = options;
	self.supported = Helper.defaultSupported();
	self.key = key;

	self._connecting = false;
	self._queueId = QueuePool.queueLength(options.server);
	self._nick = options.nick;
	self._hostname = options.hostname;
	self._user = options.user;
	self._oper = false;
	self._requestedDisconnect = false;
	self._sendRegisteredTimer;
	self._pings = 0;
	self._retryTimer = null;
	self._retryCount = 0;
	self._capCount = 0;
	self._nickModifier = 0;
	self._timedOut = false;
	self._cap = {};
	self._data = {
		user: {},
		channel: {},
		server: {}
	};
	// setup a bunch of variables to manage the state of the connection

	self.connection.setTimeout(30000, function() {
		var seconds = Math.floor((+new Date()) / 1000);
		if ((seconds - self._lastTime) >= 5 * 60) {
			self._timedOut = true;
			self.disconnect();
		} else {
			self.raw(['PING', new Date().getTime().toString()]);
		}
	});

	self.queueConnect = _.wrap(self.connection.connect, function(fn, qid) {
		QueuePool.queueJob(self.options.server, qid, self.key, function() {
			fn.call(self.connection);
			self._connecting = true;

			Events.emit([self.key, 'connecting'], {
				nickname: self._nick,
				username: self.options.user,
				server: self.options.server,
				port: self.options.port,
				localPort: self.connection.impl.localPort
			});
			// emit a connecting event
		});
	});
	// setup queueConnect

	self.queueConnect(self._queueId);
	// connect the server

	self.connection.on('connect', self._connectEvent.bind(self));
	self.connection.on('close', self._closeEvent.bind(self));
	self.connection.on('error', function() { });
	self.connection.on('data', self._parseLine.bind(self));
	// event handlers
}
300859
public function onRequest(swoole_http_request $swooleRequet, swoole_http_response $swooleResponse)
    {
        $request = SwooleServerRequest::createServerRequestFromSwoole($swooleRequet);

        $response = $this->doRequest($request);
        foreach ($response->getHeaders() as $key => $header) {
            $swooleResponse->header($key, $response->getHeaderLine($key));
        }
        foreach ($response->getCookieParams() as $key => $cookieParam) {
            $swooleResponse->cookie(
                $key,
                $cookieParam->getValue(),
                $cookieParam->getExpire(),
                $cookieParam->getPath(),
                $cookieParam->getDomain(),
                $cookieParam->isSecure(),
                $cookieParam->isHttpOnly()
            );
        }

        $swooleResponse->status($response->getStatusCode());
        $swooleResponse->end((string) $response->getBody());
        app()->shutdown($request, $response);

        return 0;
    }
700081
public function doPacket(swoole_server $server, $data, $clientInfo)
    {
        $data = Json::decode($data);
        $request = new ServerRequest($data['method'], $data['path']);
        if (isset($data['args'])) {
            if ('GET' === $request->getMethod()) {
                $request->withQueryParams($data['args']);
            } else {
                $request->withParsedBody($data['args']);
            }
        }
        $response = app()->handleRequest($request);
        $server->sendto($clientInfo['address'], $clientInfo['port'], (string) $response->getBody());
        app()->shutdown($request, $response);

        return 0;
    }
380097
def websocket(
        self, uri, host=None, strict_slashes=None, subprotocols=None, name=None
    ):
        
        self.enable_websocket()

        # Fix case where the user did not prefix the URL with a /
        # and will probably get confused as to why it's not working
        if not uri.startswith("/"):
            uri = "/" + uri

        if strict_slashes is None:
            strict_slashes = self.strict_slashes

        def response(handler):
            async def websocket_handler(request, *args, **kwargs):
                request.app = self
                if not getattr(handler, "__blueprintname__", False):
                    request.endpoint = handler.__name__
                else:
                    request.endpoint = (
                        getattr(handler, "__blueprintname__", "")
                        + handler.__name__
                    )
                try:
                    protocol = request.transport.get_protocol()
                except AttributeError:
                    # On Python3.5 the Transport classes in asyncio do not
                    # have a get_protocol() method as in uvloop
                    protocol = request.transport._protocol
                ws = await protocol.websocket_handshake(request, subprotocols)

                # schedule the application handler
                # its future is kept in self.websocket_tasks in case it
                # needs to be cancelled due to the server being stopped
                fut = ensure_future(handler(request, ws, *args, **kwargs))
                self.websocket_tasks.add(fut)
                try:
                    await fut
                except (CancelledError, ConnectionClosed):
                    pass
                finally:
                    self.websocket_tasks.remove(fut)
                await ws.close()

            self.router.add(
                uri=uri,
                handler=websocket_handler,
                methods=frozenset({"GET"}),
                host=host,
                strict_slashes=strict_slashes,
                name=name,
            )
            return handler

        return response
534949
protected function createServer()
    {
        $config = $this->getServerInitConfig();
        $this->swooleServer = new \swoole_http_server($config['host'], $config['port'], $config['mode'], $config['sockType']);
    }