Websocket upgrade as ``on_headers`` event.
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
1149789
public function onReady()
    {
        parent::onReady();
        $this->WS = \PHPDaemon\Servers\WebSocket\Pool::getInstance($this->config->wssname->value, false);
    }
104464
async def _connect_websocket(self, url, headers, engineio_path):
        """"""
        if websockets is None:  # pragma: no cover
            self.logger.error('websockets package not installed')
            return False
        websocket_url = self._get_engineio_url(url, engineio_path,
                                               'websocket')
        if self.sid:
            self.logger.info(
                'Attempting WebSocket upgrade to ' + websocket_url)
            upgrade = True
            websocket_url += '&sid=' + self.sid
        else:
            upgrade = False
            self.base_url = websocket_url
            self.logger.info(
                'Attempting WebSocket connection to ' + websocket_url)

        # get the cookies from the long-polling connection so that they can
        # also be sent the the WebSocket route
        cookies = None
        if self.http:
            cookies = '; '.join(["{}={}".format(cookie.key, cookie.value)
                                 for cookie in self.http._cookie_jar])
            headers = headers.copy()
            headers['Cookie'] = cookies

        try:
            ws = await websockets.connect(
                websocket_url + self._get_url_timestamp(),
                extra_headers=headers)
        except (websockets.exceptions.InvalidURI,
                websockets.exceptions.InvalidHandshake):
            if upgrade:
                self.logger.warning(
                    'WebSocket upgrade failed: connection error')
                return False
            else:
                raise exceptions.ConnectionError('Connection error')
        if upgrade:
            p = packet.Packet(packet.PING, data='probe').encode(
                always_bytes=False)
            try:
                await ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            try:
                p = await ws.recv()
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected recv exception: %s',
                    str(e))
                return False
            pkt = packet.Packet(encoded_packet=p)
            if pkt.packet_type != packet.PONG or pkt.data != 'probe':
                self.logger.warning(
                    'WebSocket upgrade failed: no PONG packet')
                return False
            p = packet.Packet(packet.UPGRADE).encode(always_bytes=False)
            try:
                await ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            self.current_transport = 'websocket'
            if self.http:  # pragma: no cover
                await self.http.close()
            self.logger.info('WebSocket upgrade was successful')
        else:
            try:
                p = await ws.recv()
            except Exception as e:  # pragma: no cover
                raise exceptions.ConnectionError(
                    'Unexpected recv exception: ' + str(e))
            open_packet = packet.Packet(encoded_packet=p)
            if open_packet.packet_type != packet.OPEN:
                raise exceptions.ConnectionError('no OPEN packet')
            self.logger.info(
                'WebSocket connection accepted with ' + str(open_packet.data))
            self.sid = open_packet.data['sid']
            self.upgrades = open_packet.data['upgrades']
            self.ping_interval = open_packet.data['pingInterval'] / 1000.0
            self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0
            self.current_transport = 'websocket'

            self.state = 'connected'
            client.connected_clients.append(self)
            await self._trigger_event('connect', run_async=False)

        self.ws = ws
        self.ping_loop_task = self.start_background_task(self._ping_loop)
        self.write_loop_task = self.start_background_task(self._write_loop)
        self.read_loop_task = self.start_background_task(
            self._read_loop_websocket)
        return True
649465
protected void reconfigureUpstream(ChannelPipeline pipeline, Handshake handshake) {
        pipeline.replace( "http-decoder", "websockets-decoder", handshake.newDecoder() );
        ChannelHandler[] additionalHandlers = handshake.newAdditionalHandlers();
        String currentTail = "websockets-decoder";
        for (ChannelHandler each : additionalHandlers) {
            String handlerName = "additional-" + each.getClass().getSimpleName();
            pipeline.addAfter( currentTail, handlerName, each );
            currentTail = handlerName;
        }
    }
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
889758
function onMessage(event) {
    if (!channel._websocket) return

    var message = JSON.parse(event.data)

    channel.emit("message", message)
  }
553030
def on_websocket_message(message: str) -> None:
    """"""
    msgs = json.loads(message)
    for msg in msgs:
        if not isinstance(msg, dict):
            logger.error('Invalid WS message format: {}'.format(message))
            continue
        _type = msg.get('type')
        if _type == 'log':
            log_handler(msg['level'], msg['message'])
        elif _type == 'event':
            event_handler(msg['event'])
        elif _type == 'response':
            response_handler(msg)
        else:
            raise ValueError('Unkown message type: {}'.format(message))
963122
def listen_to_event_updates():
    """"""
    def callback(event):
        print('Event:', event)

    client.create_event_subscription(instance='simulator', on_data=callback)

    sleep(5)
522703
function onUpgrade (reverseProxy, proxySocket) {
    if (!reverseProxy) {
      proxySocket.end();
      socket.end();
      return;
    }

    //
    // Any incoming data on this WebSocket to the proxy target
    // will be written to the `reverseProxy` socket.
    //
    proxySocket.on('data', listeners.onIncoming = function (data) {
      if (reverseProxy.incoming.socket.writable) {
        try {
          self.emit('websocket:outgoing', req, socket, head, data);
          var flushed = reverseProxy.incoming.socket.write(data);
          if (!flushed) {
            proxySocket.pause();
            reverseProxy.incoming.socket.once('drain', function () {
              try { proxySocket.resume() }
              catch (er) { console.error("proxySocket.resume error: %s", er.message) }
            });

            //
            // Force the `drain` event in 100ms if it hasn't
            // happened on its own.
            //
            setTimeout(function () {
              reverseProxy.incoming.socket.emit('drain');
            }, 100);
          }
        }
        catch (ex) {
          detach();
        }
      }
    });

    //
    // Any outgoing data on this Websocket from the proxy target
    // will be written to the `proxySocket` socket.
    //
    reverseProxy.incoming.socket.on('data', listeners.onOutgoing = function (data) {
      try {
        self.emit('websocket:incoming', reverseProxy, reverseProxy.incoming, head, data);
        var flushed = proxySocket.write(data);
        if (!flushed) {
          reverseProxy.incoming.socket.pause();
          proxySocket.once('drain', function () {
            try { reverseProxy.incoming.socket.resume() }
            catch (er) { console.error("reverseProxy.incoming.socket.resume error: %s", er.message) }
          });

          //
          // Force the `drain` event in 100ms if it hasn't
          // happened on its own.
          //
          setTimeout(function () {
            proxySocket.emit('drain');
          }, 100);
        }
      }
      catch (ex) {
        detach();
      }
    });

    //
    // Helper function to detach all event listeners
    // from `reverseProxy` and `proxySocket`.
    //
    function detach() {
      proxySocket.destroySoon();
      proxySocket.removeListener('end', listeners.onIncomingClose);
      proxySocket.removeListener('data', listeners.onIncoming);
      reverseProxy.incoming.socket.destroySoon();
      reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose);
      reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing);
    }

    //
    // If the incoming `proxySocket` socket closes, then
    // detach all event listeners.
    //
    proxySocket.on('end', listeners.onIncomingClose = function() {
      detach();

      // Emit the `end` event now that we have completed proxying
      self.emit('websocket:end', req, socket, head);
    });

    //
    // If the `reverseProxy` socket closes, then detach all
    // event listeners.
    //
    reverseProxy.incoming.socket.on('end', listeners.onOutgoingClose = function() {
      detach();
    });
  }
1239466
@Handler
    public void onUpgraded(Upgraded event, IOSubchannel channel) {
        if (!openChannels.contains(channel)) {
            return;
        }
        channel.respond(Output.from("/Greetings!", true));
    }
697851
def refresh(custom_headers:nil)
      response = refresh_async(custom_headers:custom_headers).value!
      response.body unless response.nil?
    end
1301706
def upgrade(self, name, params=None):
        """"""
        # Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)
        if ':' not in name:
            name = '{0}:{1}'.format(self.type, name)

        r = self._h._http_resource(
            method='PUT',
            resource=('apps', self.app.name, 'addons', quote(name)),
            params=params,
            data=' '   # Server weirdness.
        )
        r.raise_for_status()
        return self.app.addons[name]
215053
def _connect_websocket(self, url, headers, engineio_path):
        """"""
        if websocket is None:  # pragma: no cover
            # not installed
            self.logger.warning('websocket-client package not installed, only '
                                'polling transport is available')
            return False
        websocket_url = self._get_engineio_url(url, engineio_path, 'websocket')
        if self.sid:
            self.logger.info(
                'Attempting WebSocket upgrade to ' + websocket_url)
            upgrade = True
            websocket_url += '&sid=' + self.sid
        else:
            upgrade = False
            self.base_url = websocket_url
            self.logger.info(
                'Attempting WebSocket connection to ' + websocket_url)

        # get the cookies from the long-polling connection so that they can
        # also be sent the the WebSocket route
        cookies = None
        if self.http:
            cookies = '; '.join(["{}={}".format(cookie.name, cookie.value)
                                 for cookie in self.http.cookies])
        try:
            ws = websocket.create_connection(
                websocket_url + self._get_url_timestamp(), header=headers,
                cookie=cookies)
        except ConnectionError:
            if upgrade:
                self.logger.warning(
                    'WebSocket upgrade failed: connection error')
                return False
            else:
                raise exceptions.ConnectionError('Connection error')
        if upgrade:
            p = packet.Packet(packet.PING,
                              data=six.text_type('probe')).encode()
            try:
                ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            try:
                p = ws.recv()
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected recv exception: %s',
                    str(e))
                return False
            pkt = packet.Packet(encoded_packet=p)
            if pkt.packet_type != packet.PONG or pkt.data != 'probe':
                self.logger.warning(
                    'WebSocket upgrade failed: no PONG packet')
                return False
            p = packet.Packet(packet.UPGRADE).encode()
            try:
                ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            self.current_transport = 'websocket'
            self.logger.info('WebSocket upgrade was successful')
        else:
            try:
                p = ws.recv()
            except Exception as e:  # pragma: no cover
                raise exceptions.ConnectionError(
                    'Unexpected recv exception: ' + str(e))
            open_packet = packet.Packet(encoded_packet=p)
            if open_packet.packet_type != packet.OPEN:
                raise exceptions.ConnectionError('no OPEN packet')
            self.logger.info(
                'WebSocket connection accepted with ' + str(open_packet.data))
            self.sid = open_packet.data['sid']
            self.upgrades = open_packet.data['upgrades']
            self.ping_interval = open_packet.data['pingInterval'] / 1000.0
            self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0
            self.current_transport = 'websocket'

            self.state = 'connected'
            connected_clients.append(self)
            self._trigger_event('connect', run_async=False)
        self.ws = ws

        # start background tasks associated with this client
        self.ping_loop_task = self.start_background_task(self._ping_loop)
        self.write_loop_task = self.start_background_task(self._write_loop)
        self.read_loop_task = self.start_background_task(
            self._read_loop_websocket)
        return True
1050473
function apply(api, _global) {
    var WS = _global.WebSocket;
    // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
    // On older Chrome, no need since EventTarget was already patched
    if (!_global.EventTarget) {
        patchEventTarget(_global, [WS.prototype]);
    }
    _global.WebSocket = function (x, y) {
        var socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
        var proxySocket;
        var proxySocketProto;
        // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
        var onmessageDesc = ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
        if (onmessageDesc && onmessageDesc.configurable === false) {
            proxySocket = ObjectCreate(socket);
            // socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
            // but proxySocket not, so we will keep socket as prototype and pass it to
            // patchOnProperties method
            proxySocketProto = socket;
            [ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) {
                proxySocket[propName] = function () {
                    var args = ArraySlice.call(arguments);
                    if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
                        var eventName = args.length > 0 ? args[0] : undefined;
                        if (eventName) {
                            var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
                            socket[propertySymbol] = proxySocket[propertySymbol];
                        }
                    }
                    return socket[propName].apply(socket, args);
                };
            });
        }
        else {
            // we can patch the real socket
            proxySocket = socket;
        }
        patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
        return proxySocket;
    };
    var globalWebSocket = _global['WebSocket'];
    for (var prop in WS) {
        globalWebSocket[prop] = WS[prop];
    }
}
507815
async def receiver_handler(websocket):
    runner.addifnew(websocket)

    # The commented only works with python3-websockets 4.x
    '''
    
    '''

    while True:
        message = await websocket.recv()
        await consumer(websocket, message)
333140
protected function upgradeTransport()
    {
        $query = ['sid'       => $this->session->id,
                  'EIO'       => $this->options['version'],
                  'transport' => static::TRANSPORT_WEBSOCKET];

        if ($this->options['version'] === 2) {
            $query['use_b64'] = $this->options['use_b64'];
        }

        $url = \sprintf('/%s/?%s', \trim($this->url['path'], '/'), \http_build_query($query));

        $hash = \sha1(\uniqid(\mt_rand(), true), true);

        if ($this->options['version'] !== 2) {
            $hash = \substr($hash, 0, 16);
        }

        $key = \base64_encode($hash);

        $origin = '*';
        $headers = isset($this->context['headers']) ? (array) $this->context['headers'] : [] ;

        foreach ($headers as $header) {
            $matches = [];

            if (\preg_match('`^Origin:\s*(.+?)$`', $header, $matches)) {
                $origin = $matches[1];
                break;
            }
        }

        $request = "GET {$url} HTTP/1.1\r\n"
                 . "Host: {$this->url['host']}:{$this->url['port']}\r\n"
                 . "Upgrade: WebSocket\r\n"
                 . "Connection: Upgrade\r\n"
                 . "Sec-WebSocket-Key: {$key}\r\n"
                 . "Sec-WebSocket-Version: 13\r\n"
                 . "Origin: {$origin}\r\n";

        if (!empty($this->cookies)) {
            $request .= "Cookie: " . \implode('; ', $this->cookies) . "\r\n";
        }

        $request .= "\r\n";

        \fwrite($this->stream, $request);
        $result = $this->readBytes(12);

        if ('HTTP/1.1 101' !== $result) {
            throw new UnexpectedValueException(
                \sprintf('The server returned an unexpected value. Expected "HTTP/1.1 101", had "%s"', $result)
            );
        }

        // cleaning up the stream
        while ('' !== \trim(\fgets($this->stream)));

        $this->write(EngineInterface::UPGRADE);

        //remove message '40' from buffer, emmiting by socket.io after receiving EngineInterface::UPGRADE
        if ($this->options['version'] === 2) {
            $this->read();
        }
    }
840002
def listen_for_updates(self):
        """"""
        self.toredis.subscribe(self.group_pubsub, callback=self.callback)