Handles a WebSocket connection.

@param WebSocket $ws The WebSocket instance.

@return void
337144
public function handleWebSocketConnection(WebSocket $ws)
    {
        $this->logger->debug('connected to voice websocket');

        $resolver = (new DNSFactory())->createCached('8.8.8.8', $this->loop);
        $udpfac   = new DatagramFactory($this->loop, $resolver);

        $this->voiceWebsocket = $ws;

        $firstPack = true;
        $ip        = $port        = '';

        $discoverUdp = function ($message) use (&$ws, &$discoverUdp, $udpfac, &$firstPack, &$ip, &$port) {
            $data = json_decode($message->getPayload());

            if ($data->op == Op::VOICE_READY) {
                $ws->removeListener('message', $discoverUdp);

                $this->udpPort            = $data->d->port;
                $this->heartbeat_interval = $data->d->heartbeat_interval;
                $this->ssrc               = $data->d->ssrc;

                $this->logger->debug('received voice ready packet', ['data' => json_decode(json_encode($data->d), true)]);

                $this->send([
                    'op' => Op::VOICE_HEARTBEAT,
                    'd'  => microtime(true),
                ]);
                $this->emit('ws-heartbeat', []);

                $this->heartbeat = $this->loop->addPeriodicTimer($this->heartbeat_interval / 1000, function () {
                    $this->send([
                        'op' => Op::VOICE_HEARTBEAT,
                        'd'  => microtime(true),
                    ]);
                    $this->emit('ws-heartbeat', []);
                });

                $buffer = new Buffer(70);
                $buffer->writeUInt32BE($this->ssrc, 3);

                $udpfac->createClient("{$this->endpoint}:{$this->udpPort}")->then(function (Socket $client) use (&$ws, &$firstPack, &$ip, &$port, $buffer) {
                    $this->logger->debug('connected to voice UDP');
                    $this->client = $client;

                    $this->loop->addTimer(0.1, function () use (&$client, $buffer) {
                        $client->send((string) $buffer);
                    });

                    $this->udpHeartbeat = $this->loop->addPeriodicTimer(5, function () use ($client) {
                        $buffer = new Buffer(9);
                        $buffer[0] = pack('c', 0xC9);
                        $buffer->writeUInt64LE($this->heartbeatSeq, 1);
                        ++$this->heartbeatSeq;

                        $client->send((string) $buffer);
                        $this->emit('udp-heartbeat', []);
                    });

                    $client->on('error', function ($e) {
                        $this->emit('udp-error', [$e]);
                    });

                    $decodeUDP = function ($message) use (&$decodeUDP, $client, &$ip, &$port) {
                        $message = (string) $message;
                        // let's get our IP
                        $ip_start = 4;
                        $ip = substr($message, $ip_start);
                        $ip_end = strpos($ip, "\x00");
                        $ip = substr($ip, 0, $ip_end);

                        // now the port!
                        $port = substr($message, strlen($message) - 2);
                        $port = unpack('v', $port)[1];

                        $this->logger->debug('received our IP and port', ['ip' => $ip, 'port' => $port]);

                        $payload = [
                            'op' => Op::VOICE_SELECT_PROTO,
                            'd'  => [
                                'protocol' => 'udp',
                                'data'     => [
                                    'address' => $ip,
                                    'port'    => (int) $port,
                                    'mode'    => $this->mode,
                                ],
                            ],
                        ];

                        $this->send($payload);

                        $client->removeListener('message', $decodeUDP);

                        if (! $this->deaf) {
                            $client->on('message', [$this, 'handleAudioData']);
                        }
                    };

                    $client->on('message', $decodeUDP);
                }, function ($e) {
                    $this->logger->error('error while connecting to udp', ['e' => $e->getMessage()]);
                    $this->emit('error', [$e]);
                });
            }
        };

        $ws->on('message', $discoverUdp);
        $ws->on('message', function ($message) {
            $data = json_decode($message->getPayload());

            $this->emit('ws-message', [$message, $this]);

            switch ($data->op) {
                case Op::VOICE_HEARTBEAT: // keepalive response
                    $end = microtime(true);
                    $start = $data->d;
                    $diff = ($end - $start) * 1000;

                    if ($diff <= 10) { // set to 20ms
                        $this->setFrameSize(20);
                    } elseif ($diff <= 20) { // set to 40ms
                        $this->setFrameSize(40);
                    } else { // set to 60ms
                        $this->setFrameSize(60);
                    }

                    $this->emit('ws-ping', [$diff]);
                    break;
                case Op::VOICE_DESCRIPTION: // ready
                    $this->ready = true;
                    $this->mode = $data->d->mode;
                    $this->secret_key = '';

                    foreach ($data->d->secret_key as $part) {
                        $this->secret_key .= pack('C*', $part);
                    }

                    $this->logger->debug('received description packet, vc ready', ['data' => json_decode(json_encode($data->d), true)]);

                    if (! $this->reconnecting) {
                        $this->emit('ready', [$this]);
                    } else {
                        $this->reconnecting = false;
                        $this->emit('resumed', [$this]);
                    }

                    break;
                case Op::VOICE_SPEAKING: // user started speaking
                    $this->emit('speaking', [$data->d->speaking, $data->d->user_id, $this]);
                    $this->emit("speaking.{$data->d->user_id}", [$data->d->speaking, $this]);
                    $this->speakingStatus[$data->d->ssrc] = $data->d;
                    break;
            }
        });

        $ws->on('error', function ($e) {
            $this->logger->error('error with voice websocket', ['e' => $e->getMessage()]);
            $this->emit('ws-error', [$e]);
        });

        $ws->on('close', function ($op, $reason) {
            $this->logger->warning('voice websocket closed', ['op' => $op, 'reason' => $reason]);
            $this->emit('ws-close', [$op, $reason, $this]);
        });

        if (! $this->sentLoginFrame) {
            $payload = [
                'op' => Op::VOICE_IDENTIFY,
                'd'  => [
                    'server_id'  => $this->channel->guild_id,
                    'user_id'    => $this->data['user_id'],
                    'session_id' => $this->data['session'],
                    'token'      => $this->data['token'],
                ],
            ];

            $this->logger->debug('sending identify', ['packet' => $payload]);

            $this->send($payload);
            $this->sentLoginFrame = true;
        }
    }
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
        );
    }
1255515
protected function connectWs()
    {
        $this->logger->info('starting connection to websocket', ['gateway' => $this->gateway]);

        $this->wsFactory->__invoke($this->gateway)->then(
            [$this, 'handleWsConnection'],
            [$this, 'handleWsError']
        );
    }
67543
def handle_websocket(path)
      _log :ws, "#{path}: start"
      request.websocket do |ws|
        thread = nil

        ws.onopen do
          sockets << ws

          ws.send({name: :hello}.to_json)

          thread = Thread.new do
            loop do
              sleep(10)
              ws.send({name: :heartbeat}.to_json)
            end
          end
        end

        ws.onmessage do |msg|
          _log :ws, "#{path}: received message: #{msg.inspect}"
        end

        ws.onclose do
          _log :ws, "#{path}: socket closed"
          sockets.delete(ws)
          thread.kill
        end
      end
    end
434749
function(newState) {
          switch (newState) {
            case 'disconnected':
            case 'error':
              webSocket = null;
              if (onClose) {
                var error;
                if(hasLostConnectivity()) {
                  error = new Error(wsCloseErrorCodes[4001]);
                  error.code = 4001;
                }
                onClose(error);
              }
              break;
          }
        }
1055980
public function run()
    {
        $this->connect();

        while (!$this->moribund) {

            $read = $this->getReadArray();

            // Suppressing warnings for stream_select() because it will raise
            // a warning if interrupted by a signal.
            $result = @stream_select(
                $read,
                $write = null,
                $except = null,
                null
            );

            if ($result === false || $result < 1) {
                continue;
            }

            // check for new connections
            if (in_array($this->socket->getRawSocket(), $read)) {
                try {
                    $newSocket = new Net_Notifier_Socket_Accept(
                        $this->socket,
                        null
                    );
                } catch (Net_Notifier_Socket_Exception $e) {
                    $this->log(
                        'Accepting client connection failed: reason: '
                        . $e->getMessage() . PHP_EOL,
                        Net_Notifier_Logger::VERBOSITY_ERRORS
                    );
                }

                $client = new Net_Notifier_WebSocket_Connection($newSocket);
                $this->clients[] = $client;
                $this->log(
                    'client connected from ' . $client->getIPAddress()
                    . PHP_EOL,
                    Net_Notifier_Logger::VERBOSITY_CLIENT
                );
            }

            // check for client data
            foreach ($this->getReadClients($read) as $client) {

                $moribund = false;

                // check if client closed connection
                $bytes = $client->getSocket()->peek(1);

                if (mb_strlen($bytes, '8bit') === 0) {
                    $this->log(
                        sprintf(
                            'client %s closed connection.' . PHP_EOL,
                            $client->getIPAddress()
                        ),
                        Net_Notifier_Logger::VERBOSITY_CLIENT
                    );

                    $moribund = true;
                }

                try {

                    if ($client->read(self::READ_BUFFER_LENGTH)) {

                        if ($client->getState() < Net_Notifier_WebSocket_Connection::STATE_CLOSING) {

                            $receivedRelayMessage = false;
                            $messages = $client->getTextMessages();
                            foreach ($messages as $message) {
                                $this->log(
                                    sprintf(
                                        'received message: "%s" from %s'
                                        . PHP_EOL,
                                        $message,
                                        $client->getIPAddress()
                                    ),
                                    Net_Notifier_Logger::VERBOSITY_MESSAGES
                                );

                                $message = json_decode($message, true);

                                if (   $message === false
                                    || !isset($message['action'])
                                ) {
                                    $this->log(
                                        '=> incorrectly formatted' . PHP_EOL,
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    $this->startCloseClient(
                                        $client,
                                        Net_Notifier_WebSocket_Connection::CLOSE_PROTOCOL_ERROR,
                                        'Incorrectly formatted message.'
                                    );

                                    break;
                                }

                                if ($message['action'] === 'shutdown') {
                                    $this->log(
                                        sprintf(
                                            'shutting down at request of %s'
                                            . PHP_EOL,
                                            $client->getIPAddress()
                                        ),
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    $this->startCloseClient(
                                        $client,
                                        Net_Notifier_WebSocket_Connection::CLOSE_NORMAL,
                                        'Received shutdown message.'
                                    );

                                    $this->moribund = true;
                                }

                                if ($message['action'] === 'listen') {
                                    $this->log(
                                        sprintf(
                                            'set %s to listen' . PHP_EOL,
                                            $client->getIPAddress()
                                        ),
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    if (!in_array($client, $this->listenClients)) {
                                        $this->listenClients[] = $client;
                                    }
                                } else {
                                    $this->relayNotification($message);
                                    $receivedRelayMessage = true;
                                }
                            }

                            if ($receivedRelayMessage) {
                                $this->startCloseClient(
                                    $client,
                                    Net_Notifier_WebSocket_Connection::CLOSE_NORMAL,
                                    'Received message for relay.'
                                );
                            }
                        }

                    } else {

                        $this->log(
                            sprintf(
                                'got a message chunk from %s' . PHP_EOL,
                                $client->getIPAddress()
                            ),
                            Net_Notifier_Logger::VERBOSITY_CLIENT
                        );

                        if ($client->getState() === Net_Notifier_WebSocket_Connection::STATE_CLOSED) {
                            $this->log(
                                sprintf(
                                    'completed close handshake from %s'
                                    . PHP_EOL,
                                    $client->getIPAddress()
                                ),
                                Net_Notifier_Logger::VERBOSITY_CLIENT
                            );
                            $moribund = true;
                        }

                    }

                } catch (Net_Notifier_WebSocket_HandshakeFailureException $e) {
                    $this->log(
                        sprintf(
                            'failed client handshake: %s' . PHP_EOL,
                            $e->getMessage()
                        ),
                        Net_Notifier_Logger::VERBOSITY_CLIENT
                    );
                }

                if ($moribund) {
                    $this->closeClient($client);
                }

            }

        }

        $this->disconnect();
    }
636690
protected function connectWs()
	{
		$wsUrl = sprintf('ws://%s/v1/clients/%s/ws', $this->serverUrl, $this->getId());

		$this->ws = new WebsocketClient($wsUrl, ['timeout' => 30]);
		$this->ws->setTimeout(30);
	}
1077887
async def _websocket_handler(self, ws):
        """"""
        if self.connected:
            # the socket was already connected, so this is an upgrade
            self.upgrading = True  # hold packet sends during the upgrade

            try:
                pkt = await ws.wait()
            except IOError:  # pragma: no cover
                return
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.PING or \
                    decoded_pkt.data != 'probe':
                self.server.logger.info(
                    '%s: Failed websocket upgrade, no PING packet', self.sid)
                return
            await ws.send(packet.Packet(
                packet.PONG,
                data=six.text_type('probe')).encode(always_bytes=False))
            await self.queue.put(packet.Packet(packet.NOOP))  # end poll

            try:
                pkt = await ws.wait()
            except IOError:  # pragma: no cover
                return
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.UPGRADE:
                self.upgraded = False
                self.server.logger.info(
                    ('%s: Failed websocket upgrade, expected UPGRADE packet, '
                     'received %s instead.'),
                    self.sid, pkt)
                return
            self.upgraded = True

            # flush any packets that were sent during the upgrade
            for pkt in self.packet_backlog:
                await self.queue.put(pkt)
            self.packet_backlog = []
            self.upgrading = False
        else:
            self.connected = True
            self.upgraded = True

        # start separate writer thread
        async def writer():
            while True:
                packets = None
                try:
                    packets = await self.poll()
                except exceptions.QueueEmpty:
                    break
                if not packets:
                    # empty packet list returned -> connection closed
                    break
                try:
                    for pkt in packets:
                        await ws.send(pkt.encode(always_bytes=False))
                except:
                    break
        writer_task = asyncio.ensure_future(writer())

        self.server.logger.info(
            '%s: Upgrade to websocket successful', self.sid)

        while True:
            p = None
            wait_task = asyncio.ensure_future(ws.wait())
            try:
                p = await asyncio.wait_for(wait_task, self.server.ping_timeout)
            except asyncio.CancelledError:  # pragma: no cover
                # there is a bug (https://bugs.python.org/issue30508) in
                # asyncio that causes a "Task exception never retrieved" error
                # to appear when wait_task raises an exception before it gets
                # cancelled. Calling wait_task.exception() prevents the error
                # from being issued in Python 3.6, but causes other errors in
                # other versions, so we run it with all errors suppressed and
                # hope for the best.
                try:
                    wait_task.exception()
                except:
                    pass
                break
            except:
                break
            if p is None:
                # connection closed by client
                break
            if isinstance(p, six.text_type):  # pragma: no cover
                p = p.encode('utf-8')
            pkt = packet.Packet(encoded_packet=p)
            try:
                await self.receive(pkt)
            except exceptions.UnknownPacketError:  # pragma: no cover
                pass
            except exceptions.SocketIsClosedError:  # pragma: no cover
                self.server.logger.info('Receive error -- socket is closed')
                break
            except:  # pragma: no cover
                # if we get an unexpected exception we log the error and exit
                # the connection properly
                self.server.logger.exception('Unknown receive error')

        await self.queue.put(None)  # unlock the writer task so it can exit
        await asyncio.wait_for(writer_task, timeout=None)
        await self.close(wait=False, abort=True)
6965
public function attachWss($wss)
    {
        if ($this->wss->contains($wss)) {
            return false;
        }
        $this->wss->attach($wss);
        $wss->bind('customTransport', [$this, 'wsHandler']);
        return true;
    }
186119
public function run(): void
    {
        pcntl_async_signals(true);

        $this->makeSocket();

        [$pid, $master, $workers] = $this->spawn();

        if ($pid) {
            fclose($this->socket);
            $this->workerPids = $workers;
            $this->handleSignals();

            (new Master($workers, $this->unixConnector, $this->exchangeWorkersData))->dispatch();
        } else {
            if ($this->useConnector) {
                fclose($this->unixConnector);
            }

            (new $this->handler($this->socket, $master))->handle();
        }
    }
693661
function (ws, message) {
  let clientMessage;

  try {
    clientMessage = JSON.parse(message);
    /* jshint ignore:start */
    if (_.get(clientMessage, 'type') === 'message') {
      ws.send(JSON.stringify({
        ok: true,
        reply_to: _.get(clientMessage, 'id'),
        ts: Date.now(),
        message: _.get(clientMessage, 'text', message),
        type: _.get(clientMessage, 'type', 'message'),
        user: _.get(clientMessage, 'user', 'U1234567'),
        channel: _.get(clientMessage, 'channel', 'C1234567'),
      }));
    }
    /* jshint ignore:end */
  } catch (err) {
    logger.info('Invalid socket data ', message);
  }
}
709762
public function handleWebSocketError($e)
    {
        $this->logger->error('error with voice websocket', ['e' => $e->getMessage()]);
        $this->emit('error', [$e]);
    }
485647
private void _ws() throws
      IOException
  {
    builder.type = Type.S;
    // no need to preserve exact whitespace
    // but append an S char to keep the token
    // contract of always having a value
    builder.append(' ');
    reader.forward(NOT_WHITESPACE);

    if (debug)
    {
      int nxt = reader.peek();
      checkArgument(WHITESPACE.matches((char) reader.curChar));
      if (nxt > -1)
      {
        checkArgument(NOT_WHITESPACE.matches((char) nxt));
      }
    }
  }
693475
def on_close(self, ws):
        
        log.debug("Closing WebSocket connection with {}".format(self.url))
        if self.keepalive and self.keepalive.is_alive():
            self.keepalive.do_run = False
            self.keepalive.join()
1127438
public function handle(DomainMessage $domainMessage): void
    {
        $event = $domainMessage->getPayload();

        foreach ($this->sagas as $sagaType => $saga) {
            $metadata = $this->metadataFactory->create($saga);

            if (! $metadata->handles($event)) {
                continue;
            }

            $state = $this->stateManager->findOneBy($metadata->criteria($event), $sagaType);

            if (null === $state) {
                continue;
            }
            $this->eventDispatcher->dispatch(
                SagaManagerInterface::EVENT_PRE_HANDLE,
                [$sagaType, $state->getId()]
            );

            $newState = $saga->handle($event, $state);

            $this->eventDispatcher->dispatch(
                SagaManagerInterface::EVENT_POST_HANDLE,
                [$sagaType, $state->getId()]
            );

            $this->repository->save($newState, $sagaType);
        }
    }
1129355
protected function handleReconnect($data)
    {
        $this->logger->warning('received opcode 7 for reconnect');

        $this->ws->close(
            Op::CLOSE_NORMAL,
            'gateway redirecting - opcode 7'
        );
    }
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');
    }