Prepare websocket handler for onOpen and onClose callback.

@throws \Exception
768259
protected function prepareWebsocketHandler()
    {
        $handlerClass = $this->container->make('config')->get('swoole.websocket.handler', Handler::class);

        if (!$handlerClass) {
            throw new RuntimeException('Websocket handler is not set in swoole.websocket config');
        }

        $this->setWebsocketHandler($this->app->make($handlerClass));
    }
23103
async def handler(self):
    ''''''
    self.ws = await websockets.connect(self.url, ssl=self.ssl)
    while self.ws:
      message = await self.ws.recv()
      for handle in self.on_message:
        if asyncio.iscoroutinefunction(handle):
          await handle(self, message)
        else:
          handle(self, message)
871714
private function handleRequest()
    {
        //check if it's a legal webservice class
        if (!in_array($this->name, $this->classNameArr)) {
            throw new Exception('No valid webservice class.');
        }

        //check cache
        if (!file_exists($this->wsdlfile)) {
            $this->createWSDL();
        }

        $options = array('soap_version' => SOAP_1_1,
                         'actor' => $this->actor,
                         'classmap' => $this->structureMap, );

        header('Content-type: text/xml');
        $this->server = new SoapServer($this->wsdlfile, $options);
        $this->server->setClass($this->name);
        $this->server->setPersistence($this->persistence);

        use_soap_error_handler(true);
        $this->server->handle();
    }
721210
function(event) {
            event = event || {code: 1000};
            _cometd._debug('WebSocket onclose', context, event, 'connecting', _connecting, 'current', _context);

            if (context.connectTimer) {
                self.clearTimeout(context.connectTimer);
            }

            self.onClose(context, event);
        }
234765
public function onOpen($server, $swooleRequest)
    {
        $illuminateRequest = Request::make($swooleRequest)->toIlluminate();
        $websocket = $this->app->make(Websocket::class);
        $sandbox = $this->app->make(Sandbox::class);

        try {
            $websocket->reset(true)->setSender($swooleRequest->fd);
            // set currnt request to sandbox
            $sandbox->setRequest($illuminateRequest);
            // enable sandbox
            $sandbox->enable();
            // check if socket.io connection established
            if (! $this->websocketHandler->onOpen($swooleRequest->fd, $illuminateRequest)) {
                return;
            }
            // trigger 'connect' websocket event
            if ($websocket->eventExists('connect')) {
                // set sandbox container to websocket pipeline
                $websocket->setContainer($sandbox->getApplication());
                $websocket->call('connect', $illuminateRequest);
            }
        } catch (Throwable $e) {
            $this->logServerError($e);
        } finally {
            // disable and recycle sandbox resource
            $sandbox->disable();
        }
    }
1254325
public function onReady()
    {
        $this->ptr =& $this->result;
        if (!isset($this->password)) {
            if (isset($this->pool->config->select->value)) {
                $this->select($this->pool->config->select->value);
            }
            parent::onReady();
            $this->setWatermark(null, $this->pool->maxAllowedPacket + 2);
            return;
        }
        $this->sendCommand('AUTH', [$this->password], function () {
            if ($this->result !== 'OK') {
                $this->log('Auth. error: ' . json_encode($this->result));
                $this->finish();
            }
            if (isset($this->pool->config->select->value)) {
                $this->select($this->pool->config->select->value);
            }
            parent::onReady();
            $this->setWatermark(null, $this->pool->maxAllowedPacket + 2);
        });
    }
1065714
public function listen()
    {

        if (!$this->_socketName || $this->_mainSocket) {
            return;
        }

        // Autoload.
        Autoloader::setRootPath($this->_autoloadRootPath);

        // Get the application layer communication protocol and listening address.
        list($scheme, $address) = explode(':', $this->_socketName, 2);
        // Check application layer protocol class.
        if (!isset(self::$_builtinTransports[$scheme])) {
            if(class_exists($scheme)){
                $this->protocol = $scheme;
            } else {
                $scheme         = ucfirst($scheme);
                $this->protocol = '\\Protocols\\' . $scheme;
                if (!class_exists($this->protocol)) {
                    $this->protocol = "\\Workerman\\Protocols\\$scheme";
                    if (!class_exists($this->protocol)) {
                        throw new Exception("class \\Protocols\\$scheme not exist");
                    }
                }
            }
            if (!isset(self::$_builtinTransports[$this->transport])) {
                throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
            }
        } else {
            $this->transport = $scheme;
        }

        $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;

        // Flag.
        $flags  = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
        $errno  = 0;
        $errmsg = '';
        // SO_REUSEPORT.
        if ($this->reusePort) {
            stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
        }

        // Create an Internet or Unix domain server socket.
        $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
        if (!$this->_mainSocket) {
            throw new Exception($errmsg);
        }

        if ($this->transport === 'ssl') {
            stream_socket_enable_crypto($this->_mainSocket, false);
        }

        // Try to open keepalive for tcp and disable Nagle algorithm.
        if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
            $socket = socket_import_stream($this->_mainSocket);
            @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
            @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
        }

        // Non blocking.
        stream_set_blocking($this->_mainSocket, 0);

        // Register a listener to be notified when server socket is ready to read.
        if (self::$globalEvent) {
            if ($this->transport !== 'udp') {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
            } else {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
                    array($this, 'acceptUdpConnection'));
            }
        }
    }
275353
public function start()
    {
        $__scope = $this->_runHooks($this->_startHooks);
        extract($__scope);
        
        $this->_write($this->_socket, self::READY);
        
        /* Note the naming of the local variables due to shared scope with the user here */
        for (;;) {
            declare (ticks = 1);
            // don't exit on ctrl-c
            pcntl_signal(SIGINT, SIG_IGN, true);
            
            $this->_cancelled = false;
            
            $__input = $this->_transform($this->_read($this->_socket));
            
            if ($__input === null) {
                continue;
            }
            
            $__response = self::DONE;
            
            $this->_ppid = posix_getpid();
            $this->_pid  = pcntl_fork();
            
            if ($this->_pid < 0) {
                throw new \RuntimeException('Failed to fork child labourer');
            } elseif ($this->_pid > 0) {
                // kill the child on ctrl-c
                pcntl_signal(SIGINT, array(
                    $this,
                    'cancelOperation'
                ), true);
                pcntl_waitpid($this->_pid, $__status);
                
                if (!$this->_cancelled && $__status != (self::ABNORMAL_EXIT << 8)) {
                    $__response = self::EXITED;
                } else {
                    $this->_runHooks($this->_failureHooks);
                    $__response = self::FAILED;
                }
            } else {
                // if the user has installed a custom exception handler, install a new
                // one which calls it and then (if the custom handler didn't already exit)
                // exits with the correct status.
                // If not, leave the exception handler unset; we'll display
                // an uncaught exception error and carry on.
                $__oldexh = set_exception_handler(array(
                    $this,
                    'delegateExceptionHandler'
                ));
                if ($__oldexh && !$this->_userExceptionHandler) {
                    $this->_userExceptionHandler = $__oldexh; // save the old handler (once)
                } else {
                    restore_exception_handler();
                }
                
                // undo ctrl-c signal handling ready for user code execution
                pcntl_signal(SIGINT, SIG_DFL, true);
                $__pid = posix_getpid();
                
                $__result = eval($__input);
                
                if (posix_getpid() != $__pid) {
                    // whatever the user entered caused a forked child
                    // (totally valid, but we don't want that child to loop and wait for input)
                    exit(0);
                }
                
                if (preg_match('/\s*return\b/i', $__input)) {
                    fwrite(STDOUT, sprintf("%s\n", $this->_inspector->inspect($__result)));
                }
                $this->_expungeOldWorker();
            }
            
            $this->_write($this->_socket, $__response);
            
            if ($__response == self::EXITED) {
                exit(0);
            }
        }
    }
1372581
public function onOpen(\Swoole\WebSocket\Server $server, \Swoole\Http\Request $request)
    {
        // echo "[websocket][onopen]server: handshake success with fd{$request->fd} url={$request->server['request_uri']}?{$request->server['query_string']}\n";

        // Compat fpm server
        $this->_compatFPM($request);

        // print_r(self::$websocketFrameContext);

        // filter websocket router class
        // route struct: [$controller_name, $controller_class]
        $controller_class = (\ePHP\Core\Route::init())->findWebSocketRoute();
        if ( !empty($controller_class) ) {
            // Save websocket connection Context
            self::$websocketFrameContext[$request->fd] = [
                'get'    => $_GET,
                'cookie' => $_COOKIE,
                'controller_class' => $controller_class
            ];

            // echo 'pid='. getmypid() . ', fd=' . implode(',', array_keys(self::$websocketFrameContext))
            //     . ', connections=' . count($this->server->connections) . "\n";

            call_user_func([new $controller_class(), 'onOpen'], $server, $request);
        }

    }
1149789
public function onReady()
    {
        parent::onReady();
        $this->WS = \PHPDaemon\Servers\WebSocket\Pool::getInstance($this->config->wssname->value, false);
    }
474437
async def handle_websocket_exception(self, error: Exception) -> Optional[Response]:
        
        await got_websocket_exception.send(self, exception=error)

        self.log_exception(sys.exc_info())

        internal_server_error = all_http_exceptions[500]()
        handler = self._find_exception_handler(internal_server_error)

        if handler is None:
            return internal_server_error.get_response()
        else:
            return await self.finalize_websocket(await handler(error), from_error_handler=True)
294681
private function handleWebhook() {
        $identifier = $this->field('identifier');

        if ($identifier !== $this->identifier) {
            return;
        }

        $event_id = $this->field('event_id');
        $webhook_id = $this->field('webhook_id');

        if (!$event_id || !$webhook_id) {
            Log::info($this->patrol, 'Webhook ' . $this->identifier . ' has no event_id or webhook_id');
            return;
        }

        $httpClient = new HttpClient($this->patrol, 'GET', 'webhooks/' . $webhook_id . '/events/' . $event_id);
        $response = $httpClient->response();

        if (!$response) {
            Log::info($this->patrol, 'Retrieving webhook from ' . $httpClient->getUrl() . ' failed');
            return;
        }

        $data = $this->field($response, 'data');

        if (!$data) {
            Log::info($this->patrol, 'Event has invalid format to be processed: ' . print_r($response, true));
        }

        $callable = $this->callback;

        if (is_callable($callable)) {
            $callable($data);
        }
    }
966266
function (pres)
    {
        if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
            if (pres) {
                this._conn.send(pres);
            }
            var close = $build("close", { "xmlns": Strophe.NS.FRAMING, });
            this._conn.xmlOutput(close);
            var closeString = Strophe.serialize(close);
            this._conn.rawOutput(closeString);
            try {
                this.socket.send(closeString);
            } catch (e) {
                Strophe.info("Couldn't send <close /> tag.");
            }
        }
        this._conn._doDisconnect();
    }
501749
protected function openHandle()
    {
        $fileName = $this->getFileName();

        $this->_handle = fopen($fileName, 'w');

        if (!$this->_handle) {
            throw new \Exception('Cannot open file ' . $fileName);
        }
    }
26801
public function handleShutdown()
    {
        $error = $this->system->getLastError();
        if ($error === null) {
            return;
        }
        if (($error['type'] & error_reporting()) === 0) {
            return;
        }
        if ($this->lastError !== null &&
            $error['message'] === $this->lastError['message'] &&
            $error['file'] === $this->lastError['file'] &&
            $error['line'] === $this->lastError['line']) {
            return;
        }
        $trace = [[
            'file' => $error['file'],
            'line' => $error['line'],
        ]];
        $exc = new Fatal($error['message'], $trace);
        $notice = $this->buildNotice($exc);

        // If we reached this step, we are in shutdown handler.
        // An exception thrown in a shutdown handler will not be propagated
        // to the exception handler. Pass that information along.
        $this->canThrowExceptions = false;

        if ($error && $this->isLevelFatal($error['type'])) {
            // If there was a fatal error,
            // it was not handled in handleError yet.
            $this->handleError(
                $error['type'],
                $error['message'],
                $error['file'],
                $error['line']
            );
        }
		if($error["type"] != 0) {
            //call_user_func($this->errorHandler,new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']));
			//log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
		}
    }
1083155
public function onAfterRoute()
    {
        $app = JFactory::getApplication();

        $username = $app->input->server->get('PHP_AUTH_USER', null, 'string');
        $password = $app->input->server->get('PHP_AUTH_PW', null, 'string');

        if ($username && $password)
        {
            if (!$this->_login($username, $password, $app)) {
                throw new Exception('Login failed', 401);
            }
        }
    }
853383
protected function prepareExecute()
    {
        if (!($this->console instanceof Console\AbstractConsole)) {
            throw new \Exception('RootCommand::$app should have Console Application');
        }

        if (!$this->getOption('ansi') || strtolower($this->getOption('ansi')) === 'off') {
            $this->console->set('ansi', false);

            $this->io->useColor(false);
        }

        if ($this->getOption('quiet')) {
            $this->console->set('quiet', true);
        }

        if ($this->getOption('verbose')) {
            $this->console->set('verbose', true);
        }

        if ($this->getOption('help')) {
            $this->console->set('show_help', true);
        }
    }