Upgrades the transport to WebSocket

FYI:
Version "2" is used for the EIO param by socket.io v1
Version "3" is used by socket.io v2
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();
        }
    }
387774
private void configureHttp2UpgradePipeline(ChannelPipeline pipeline, HttpClientCodec sourceCodec,
                                               TargetHandler targetHandler) {
        pipeline.addLast(sourceCodec);
        addCommonHandlers(pipeline);
        Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(http2ConnectionHandler);
        HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec,
                Integer.MAX_VALUE);
        pipeline.addLast(Constants.HTTP2_UPGRADE_HANDLER, upgradeHandler);
        pipeline.addLast(Constants.TARGET_HANDLER, targetHandler);
    }
39247
function updateWeibo(data){
  if(!data.accessToken){
    throw new Error('need a accessToken');
  }
  var emitter = new Emitter();
  
  var msg = data.message
    , coordinates = data.coordinates
    , img = data.image;
    
  var body = "status=" + encodeURIComponent(msg),
    url, headers, multipart;
    
  //console.log('last text: ' + msg);
  //console.log('coordinates: ' + util.inspect(coordinates));
  
  body += (coordinates && coordinates.length == 2) ? ('&lat=' + encodeURIComponent(coordinates[1]) + '&long=' + encodeURIComponent(coordinates[0])) : '';
  
  if(img){
    url = 'https://api.weibo.com/2/statuses/upload.json?access_token=' + data.accessToken;
    headers = {"content-type": "multipart/form-data"};
    body = '';
  }else{
    url = 'https://api.weibo.com/2/statuses/update.json?access_token=' + data.accessToken;
    headers = {"Content-Type": "application/x-www-form-urlencoded"};
  }
  
  if(img && !Buffer.isBuffer(img)){
    if(/^https?\:\/\//i.test(img)){
      request({url: img, encoding: null}, function(err, res, img){
        if(err){
          emitter.emit('error', err);
        }else{
          multipart = multipartParse(msg, coordinates, img);
          //console.log(util.inspect(multipart))
          //console.log(headers)
          faWeibo(url, headers, body, multipart, emitter);
        }
      });
    }else{
      emitter.emit('error', 'need a image');
    }
  }else{
    if(img){//buffer
      multipart = multipartParse(msg, coordinates, img);
    }
    
    faWeibo(url, headers, body, multipart, emitter);
  }
  return emitter;
}
634374
function WebSocketRepeater (options) {
    var self = this;
    if (!options) { options = {}; }

    var port = options.port || 8080;
    var clientCount = 0;
    var idCounter = 0;

    this.clients = [];

    var wss;

    if (options.server) {
        wss = new WebSocketServer({server: options.server});
    } else {
        wss = new WebSocketServer({port: port});
    }

    // websocket connections
    wss.on('connection', function(ws) {
        var clientInfo = {
            ws: ws,
            cid: ++idCounter,
            errored: false
        };
        self.clients.push(clientInfo);
        clientCount++;

        ws.on('message', function(message) {
            self.emit('message', message, ws);

            var messageJSON;
            var responce;

            self.clients.forEach(function (client) {
                if (client.cid !== clientInfo.cid) {
                    client.ws.send(message);
                }
            });

            // try {
            //     messageJSON = JSON.parse(message);
            // } catch (e) {}

            // if (messageJSON) {
            //     testAllRoutes(routes, ws, messageJSON);
            // } 
        });

        ws.on('close', function() {
            self.clients = _.without(self.clients, clientInfo);
            --clientCount;
            logClientCount();
        });

        ws.on('error', function () {
            logClientCount();
            clientInfo.errored = true;
        });

        logClientCount();
    });

    // start the heat beat
    if (options.useHeartbeat) {
        this.heartbeat();
    }

    function logClientCount() {
        console.log("Client count ", clientCount);
    }

}
763782
private <T,S> void upgradeWebSocket(ServiceWebSocket<T,S> service)
  {
    /*
    try {
      _service.open((WebRequest) request);
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }
    */
    TypeRef type = TypeRef.of(service.getClass()).to(ServiceWebSocket.class).param(0);

    ServiceRef selfRef = ServiceRef.current();

    service = selfRef.pin(service).as(ServiceWebSocket.class);

    Class<T> rawClass = (Class) type.rawClass();

    WebSocketBaratineImpl<T,S> ws
      = new WebSocketBaratineImpl<>(webApp().wsManager(),
                                    service, rawClass);

    try {
      if (! ws.handshake(this)) {
        throw new ServiceException("WebSocket handshake failed for " + this);
      }
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
      e.printStackTrace();

      fail(e);
    }
    //request.flush();
  }
714659
function CoapServer(options) {
  // Superclass Constructor
  EventEmitter.call(this);

  options = options || {};
  this.clientsPath = [];
  this.host = options.host || 'localhost';
  this.port = options.port || 8000;
  this.endpoints = options.endpoints || [];  
  this.websocketEndpoints = {};

  this.route = {};
  this.handlers = {};
  this.server = null;
}
146097
public void upgradeToSecure() throws IOException {
        Options options = this.connection.getOptions();
        SSLContext context = options.getSslContext();
        
        SSLSocketFactory factory = context.getSocketFactory();
        Duration timeout = options.getConnectionTimeout();

        this.sslSocket = (SSLSocket) factory.createSocket(socket, null, true);
        this.sslSocket.setUseClientMode(true);

        final CompletableFuture<Void> waitForHandshake = new CompletableFuture<>();
        
        this.sslSocket.addHandshakeCompletedListener((evt) -> {
            waitForHandshake.complete(null);
        }
193545
public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory,
      HostnameVerifier hostnameVerifier, Socket socket, String host, int port,
      ConnectionSpec spec) throws IOException {
    Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory");
    Preconditions.checkNotNull(socket, "socket");
    Preconditions.checkNotNull(spec, "spec");
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
        socket, host, port, true /* auto close */);
    spec.apply(sslSocket, false);
    String negotiatedProtocol = OkHttpProtocolNegotiator.get().negotiate(
        sslSocket, host, spec.supportsTlsExtensions() ? TLS_PROTOCOLS : null);
    Preconditions.checkState(
        TLS_PROTOCOLS.contains(Protocol.get(negotiatedProtocol)),
        "Only " + TLS_PROTOCOLS + " are supported, but negotiated protocol is %s",
        negotiatedProtocol);

    if (hostnameVerifier == null) {
      hostnameVerifier = OkHostnameVerifier.INSTANCE;
    }
    if (!hostnameVerifier.verify(canonicalizeHost(host), sslSocket.getSession())) {
      throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }
    return sslSocket;
  }
258159
function Socket (options) {
    this.options = {
        port: 80
      , secure: false
      , document: 'document' in global ? document : false
      , resource: 'socket.io'
      , transports: io.transports
      , 'connect timeout': 10000
      , 'try multiple transports': true
      , 'reconnect': true
      , 'reconnection delay': 500
      , 'reconnection limit': Infinity
      , 'reopen delay': 3000
      , 'max reconnection attempts': 10
      , 'sync disconnect on unload': true
      , 'auto connect': true
      , 'flash policy port': 10843
    };

    io.util.merge(this.options, options);

    this.connected = false;
    this.open = false;
    this.connecting = false;
    this.reconnecting = false;
    this.namespaces = {};
    this.buffer = [];
    this.doBuffer = false;

    if (this.options['sync disconnect on unload'] &&
        (!this.isXDomain() || io.util.ua.hasCORS)) {
      var self = this;

      io.util.on(global, 'unload', function () {
        self.disconnectSync();
      }, false);
    }

    if (this.options['auto connect']) {
      this.connect();
    }
}
1244330
async def _upgrade_websocket(self, environ):
        """"""
        if self.upgraded:
            raise IOError('Socket has been upgraded already')
        if self.server._async['websocket'] is None:
            # the selected async mode does not support websocket
            return self.server._bad_request()
        ws = self.server._async['websocket'](self._websocket_handler)
        return await ws(environ)
712454
protected boolean isWebSocketsUpgradeRequest(HttpRequest request) {
        String connectionHeader = request.getHeader( Names.CONNECTION );
        String upgradeHeader = request.getHeader( Names.UPGRADE );

        if (connectionHeader == null || upgradeHeader == null) {
            return false;
        }

        if (connectionHeader.trim().toLowerCase().contains( Values.UPGRADE.toLowerCase() )) {
            if (upgradeHeader.trim().equalsIgnoreCase( Values.WEBSOCKET )) {
                return true;
            }
        }

        return false;
    }
731603
function IopaHttp(app) {
  app.properties[SERVER.Capabilities][HTTP.CAPABILITY] = {};
  app.properties[SERVER.Capabilities][HTTP.CAPABILITY][SERVER.Version] = packageVersion;
  app.properties[SERVER.Capabilities][HTTP.CAPABILITY][IOPA.Protocol] = HTTP.PROTOCOLVERSION;

  this.app = app;
}
392354
def update_nio(self, port_number, nio):
        

        bridge_name = "{}-{}".format(self._id, port_number)
        if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():
            yield from self._ubridge_apply_filters(bridge_name, nio.filters)
382845
def upgrade_api(request, client, version):
    """"""

    min_ver, max_ver = api_versions._get_server_version_range(client)
    if min_ver <= api_versions.APIVersion(version) <= max_ver:
        client = _nova.novaclient(request, version)
    return client
880430
def setup_handler(self, io_loop):
		

		if self.server_mode() is True:
			s = self.transport().server_socket(self.config())
		else:
			s = self.transport().client_socket(self.config())

		io_handler = self.io_handler()
		if isinstance(io_handler, WNativeSocketDirectIOHandler) is True:
			io_handler.transport_socket(s)
		io_loop.add_handler(s.fileno(), io_handler.handler_fn, io_loop.READ)
634496
public void upgrade(ConnectionProtocol upgrade)
  {
    connHttp().request(upgrade);
    //_upgrade = upgrade;
    
    //upgrade.start();
    
    requestHttp().upgrade();
    
    _state = _state.toUpgrade();
    
    requestHttp().connTcp().proxy().requestWake();
  }
73080
function SocketIo(gameServer) {

    /**
     * ### SocketIo.name
     *
     * The name of the socket.
     */
    this.name = 'sio';

    /**
     * ### Socket.gameServer
     *
     * Reference to the game server in which the socket is created.
     *
     * @see GameServer
     */
    this.gameServer = gameServer;

    /**
     * ### Socket.sio
     *
     * Reference to the Socket.IO app of the game server
     *
     * @see GameServer
     */
    this.sio = this.gameServer.sio;

    /**
     * ### SocketIo.sioChannel
     *
     * The Socket.IO internal channel
     */
    this.sioChannel = null;

    /**
     * ### SocketIo.sidPrefix
     *
     * The prefix to be added to the id of every client connected to the socket
     *
     * Must have exactly 2 characters and be unique for every socket.
     */
    this.sidPrefix = this.gameServer.ADMIN_SERVER ? 'SA' : 'SP';

    /**
     * ### SocketIo.sidPrefixStrip
     *
     * The prefix to be stripped from sid for internal operations
     *
     * Sids are represented as SA/endpoint#sid, but in sockets.connected
     * they are saved as /#sid. Note: endpoints already start with a /.
     *
     * Notice: this depends on how Socket.io represets sid internally.
     * If they change the internal structure it needs to be adapted.
     *
     * @see SocketIo.disconnect
     */
    this.sidPrefixStrip = this.sidPrefix + this.gameServer.endpoint;

    /**
     * ### SocketIo.sidPrefixStripLen
     *
     * The length of the prefix to be stripped from sid for internal operations
     *
     * @see SocketIo.sidPrefixStrip
     * @see SocketIo.disconnect
     */
    this.sidPrefixStripLen = this.sidPrefixStrip.length;
}