Handles WebSocket connections received by the client.

@param WebSocket $ws WebSocket client.
778706
public function handleWsConnection(WebSocket $ws)
    {
        $this->ws        = $ws;
        $this->connected = true;

        $this->logger->info('websocket connection has been created');

        $ws->on('message', [$this, 'handleWsMessage']);
        $ws->on('close', [$this, 'handleWsClose']);
        $ws->on('error', [$this, 'handleWsError']);
    }
709762
public function handleWebSocketError($e)
    {
        $this->logger->error('error with voice websocket', ['e' => $e->getMessage()]);
        $this->emit('error', [$e]);
    }
1093573
function Connection(ws, logger) {
        events.EventEmitter.call(this);

        this._ws = ws;
        this._logger = logger;
        this._connected = true;

        this._ws.on("message", this._receive.bind(this));
        this._ws.once("close", this.close.bind(this));
    }
324037
public function onWebsocketConnect($connection, $http_buffer)
    {
        $this->sendToWorker(GatewayProtocol::CMD_ON_WEBSOCKET_CONNECT, $connection, array('get' => $_GET, 'server' => $_SERVER, 'cookie' => $_COOKIE));
    }
964107
public void connect() throws ConnectException {
        try {
            connectToWebSocket();
            setWebSocketListener();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("Interrupted while connecting via WebSocket protocol");
        }
    }
1280799
function connectBrowser (subscriptions, backlog, host, done_cb, secure) {

    // Associate the right port
    var websocket_uri;
    if(secure == true) {
        websocket_uri ='wss://' + host + ':1885/mqtt';
    }
    else {
        websocket_uri ='ws://' + host + ':1884/mqtt';
    }

    // Create client
    var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
    // Register callback for connection lost
    client.onConnectionLost = function() {
        // TODO try to reconnect
    };
    // Register callback for received message
    client.onMessageArrived = function (message) {
        // Execute all the appropriate callbacks:
        // the ones specific to this channel with a single parameter (message)
        // the ones associated to a wildcard channel, with two parameters (message and channel)
        var cbs = findCallbacks(subscriptions, message.destinationName);
        if (cbs!==undefined) {
            cbs.forEach(function(cb) {
                if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
                    cb(message.payloadString);
                else
                    cb(message.payloadString, message.destinationName);
            });
        }
    };
    // Connect
    client.connect({onSuccess: function() {
        // Execute optional done callback passing true
        if (done_cb!==undefined)
            done_cb(true);
        // Execute the backlog of operations performed while the client wasn't connected
        backlog.forEach(function(e) {
            e.op.apply(this, e.params);
        });
    },
        onFailure: function() {
            // Execute optional done callback passing false
            if (done_cb!==undefined)
                done_cb(false);
            else
                console.error('There was a problem initializing nutella.');
        }});
    return client;
}
399976
protected function connect()
    {
        $this->socket = new Net_Notifier_Socket_Client(
            sprintf(
                'tcp://%s:%s',
                $this->host,
                $this->port
            ),
            $this->timeout / 1000
        );

        $this->connection = new Net_Notifier_WebSocket_Connection(
            $this->socket
        );

        $this->connection->startHandshake(
            $this->host,
            $this->port,
            $this->resource,
            array(Net_Notifier_WebSocket::PROTOCOL)
        );

        // read handshake response
        $state = $this->connection->getState();
        while ($state < Net_Notifier_WebSocket_Connection::STATE_OPEN) {

            $read = array($this->socket->getRawSocket());

            $result = stream_select(
                $read,
                $write = null,
                $except = null,
                null
            );

            if ($result === 1) {
                $this->connection->read(self::READ_BUFFER_LENGTH);
            }

            $state = $this->connection->getState();
        }
    }
254599
def on_open(self, ws):
        
        self.callback.on_connected()

        # Send initialization message
        init_data = self.build_start_message(self.options)
        self.ws_client.send(json.dumps(init_data).encode('utf8'), websocket.ABNF.OPCODE_TEXT)
651779
def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # handle known errors, will reconnect
      on_close(exc.code, exc.reason)

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect
      on_close(1006, exc.message)

    rescue => exc
      # TODO: crash instead of reconnecting on unknown errors?
      error exc
      on_close(1006, exc.message)

    else
      # client closed, not going to happen
      on_close(ws.close_code, ws.close_reason)

    ensure
      @ws = nil

      ws.disconnect
    end
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()
875700
public function handleWsError($e)
    {
        // Pawl pls
        if (strpos($e->getMessage(), 'Tried to write to closed stream') !== false) {
            return;
        }

        $this->logger->error('websocket error', ['e' => $e->getMessage()]);
        $this->emit('error', [$e, $this]);

        $this->handleWsClose(0, 'websocket error');
    }
935864
@Override
	public void handleMessageToClient(WebSocketSession session, Message<?> message) {
		if (!(message instanceof WampMessage)) {
			logger.error("Expected WampMessage. Ignoring " + message + ".");
			return;
		}

		boolean closeWebSocketSession = false;
		try {
			String json = ((WampMessage) message).toJson(this.jsonFactory);
			session.sendMessage(new TextMessage(json));
		}
		catch (SessionLimitExceededException ex) {
			// Bad session, just get out
			throw ex;
		}
		catch (Throwable ex) {
			// Could be part of normal workflow (e.g. browser tab closed)
			logger.debug("Failed to send WebSocket message to client in session "
					+ session.getId() + ".", ex);
			closeWebSocketSession = true;
		}
		finally {
			if (closeWebSocketSession) {
				try {
					session.close(CloseStatus.PROTOCOL_ERROR);
				}
				catch (IOException ex) {
					// Ignore
				}
			}
		}
	}
774185
def _websocket_handler(self, ws):
        """"""
        # try to set a socket timeout matching the configured ping interval
        for attr in ['_sock', 'socket']:  # pragma: no cover
            if hasattr(ws, attr) and hasattr(getattr(ws, attr), 'settimeout'):
                getattr(ws, attr).settimeout(self.server.ping_timeout)

        if self.connected:
            # the socket was already connected, so this is an upgrade
            self.upgrading = True  # hold packet sends during the upgrade

            pkt = ws.wait()
            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 []
            ws.send(packet.Packet(
                packet.PONG,
                data=six.text_type('probe')).encode(always_bytes=False))
            self.queue.put(packet.Packet(packet.NOOP))  # end poll

            pkt = ws.wait()
            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:
                self.queue.put(pkt)
            self.packet_backlog = []
            self.upgrading = False
        else:
            self.connected = True
            self.upgraded = True

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

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

        while True:
            p = None
            try:
                p = ws.wait()
            except Exception as e:
                # if the socket is already closed, we can assume this is a
                # downstream error of that
                if not self.closed:  # pragma: no cover
                    self.server.logger.info(
                        '%s: Unexpected error "%s", closing connection',
                        self.sid, str(e))
                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:
                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')
                break

        self.queue.put(None)  # unlock the writer task so that it can exit
        writer_task.join()
        self.close(wait=False, abort=True)

        return []
676994
@Override
    public void handleMessage(@Sensitive Message message) throws Fault {

        //if no wsrinfo, we will not override the port address & client prop
        if (wsrInfo != null) {
            customizePortAddress(message);
            customizeClientProperties(message);
        }

        customizeClientSecurity(message);

    }
175260
public function handleConnect(
        \Erebot\Interfaces\EventHandler $handler,
        \Erebot\Interfaces\Event\Connect $event
    ) {
        $this->connected = true;
    }
966658
public function handle()
    {
        if (substr($_SERVER['QUERY_STRING'], -4) == 'wsdl') {
            $this->showWSDL();

            return;
        }
        if ($this->isSoapRequest()) {
            $this->handleRequest();
        } else {
            $this->createDocumentation();
        }
    }
54682
protected function handleConnectEncoding(array &$querystring) {
        if($this->encoding === null) {
            $encoding = $querystring['encoding'] ?? self::WS['encoding'];
            
            $name = \str_replace('-', '', \ucwords($encoding, '-'));
            if(\strpos($name, '\\') === false) {
                $name = '\\CharlotteDunois\\Yasmin\\WebSocket\\Encoding\\'.$name;
            }
            
            $name::supported();
            
            $interfaces = \class_implements($name);
            if(!\in_array('CharlotteDunois\\Yasmin\\Interfaces\\WSEncodingInterface', $interfaces)) {
                throw new \RuntimeException('Specified WS encoding class does not implement necessary interface');
            }
            
            $this->encoding = new $name();
            $querystring['encoding'] = $this->encoding->getName();
        }
    }