Websocket Client Demo
487115
public function websocketClient()
    {
        $this->writeln('Starting demo websocket client...');

        $client = new Client(
            'ws://' .
            ($this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST) . ':' .
            ($this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT)
        );
        $client->send(JsonHelper::encode(['handler' => SwooleTcpJob::class]));
        $this->writeln($client->receive());
        $client->close();
    }
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;
}
310163
function() {
  EventEmitter.call(this);
  this.httpServer = new HttpServer();

  var self = this;
  this.wsServer = new WebSocketServer({server: this.httpServer});

  this.wsServer.on('connection', function(socket) {
    // emit socket to outside
    self.emit('connection', socket);
  });

  this.state = ST_STARTED;
}
813855
function WebSocket(socket, ctx) {
  if (!(this instanceof WebSocket))
    return new WebSocket(socket, ctx);

  EventEmitter.call(this);

  this.context = ctx;
  this.socket = socket;
  this.remoteAddress = socket.conn.remoteAddress;
  this.hooks = Object.create(null);
  this.channels = new Map();
  this.auth = false;
  this.filter = null;
  this.prev = null;
  this.next = null;

  this.init();
}
683838
def on_open(self, websocket):
        ''''''
        LOGGER.info('New websocket opened. Add client to %s on "%s" channel',
                    self.pubsub, self.channel)
        self.pubsub.add_client(self.client(websocket, self.channel))
611257
async def open_websocket_client(sock: anyio.abc.SocketStream,
                                addr,
                                path: str,
                                headers: Optional[list] = None,
                                subprotocols: Optional[list] = None):
    """"""
    ws = await create_websocket_client(
        sock, addr=addr, path=path, headers=headers, subprotocols=subprotocols)
    try:
        yield ws
    finally:
        await ws.close()
765847
def send_msg_to_clients(client_ids, msg, error=False):
    """"""
    if error:
        stream = "stderr"
    else:
        stream = "stdout"

    response = [{"message": None, "type": "console", "payload": msg, "stream": stream}]

    for client_id in client_ids:
        logger.info("emiting message to websocket client id " + client_id)
        socketio.emit(
            "gdb_response", response, namespace="/gdb_listener", room=client_id
        )
557330
def on_start(self, host, port, channel, nickname, password):
        
        self.client = WebSocketIRCClient(host, port, channel, nickname,
                                         password, self)
        self.spawn(self.client.start)
953
def chat(ws):
    
    lag_tolerance_secs = float(request.args.get("tolerance", 0.1))
    client = Client(ws, lag_tolerance_secs=lag_tolerance_secs)
    client.subscribe(request.args.get("channel"))
    gevent.spawn(client.heartbeat)
    client.publish()
699989
def _authenticate_websocket(self, websocket, event_handler):
		
		log.debug('Authenticating websocket')
		json_data = json.dumps({
			"seq": 1,
			"action": "authentication_challenge",
			"data": {
				"token": self._token
			}
		}).encode('utf8')
		yield from websocket.send(json_data)
		while True:
			message = yield from websocket.recv()
			status = json.loads(message)
			log.debug(status)
			# We want to pass the events to the event_handler already
			# because the hello event could arrive before the authentication ok response
			yield from event_handler(message)
			if ('status' in status and status['status'] == 'OK') and \
					('seq_reply' in status and status['seq_reply'] == 1):
				log.info('Websocket authentification OK')
				return True
			elif 'seq_reply' in status and status['seq_reply'] == 1:
				log.error('Websocket authentification failed')
990684
function onLauncherConnect(slaveURL) {
    var browsers = attester.config["run-browser"];
    if (browsers) {
        if (!Array.isArray(browsers)) {
            browsers = [browsers];
        }
        var args = [slaveURL];
        for (var i = 0, l = browsers.length; i < l; i++) {
            var curProcess = spawn(browsers[i], args, {
                stdio: "pipe"
            });
            curProcess.stdout.pipe(process.stdout);
            curProcess.stderr.pipe(process.stderr);
        }
    }
}
763491
function Client (globalRequest, maxSockets) {
  var emptyResponse = JSON.parse(JSON.stringify(response))
  var body = ''
  var httpAgent = null
  var httpsAgent = null

  if (maxSockets) {
    httpAgent = new http.Agent({ maxSockets: maxSockets })
    httpsAgent = new https.Agent({ maxSockets: maxSockets })
  }

  // utility function to create an empty request object
  this.emptyRequest = function () {
    return JSON.parse(JSON.stringify(request))
  }

  // utility function to detect empty objects
  function isEmpty (obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        return false
      }
    }
    return true
  }

  // add query paramaters to a URL
  function buildPath (basePath, queryParams) {
    basePath = basePath.concat('?')
    var url = basePath.concat(queryString.stringify(queryParams))
    return url
  }

  function buildRequest (globalRequest, endpointRequest) {
    var request = JSON.parse(JSON.stringify(globalRequest))
    request.host = endpointRequest.host || globalRequest.host
    request.method = endpointRequest.method

    if (endpointRequest.port) {
      request.port = endpointRequest.port
    }

    // build URL
    request.path = !isEmpty(endpointRequest.queryParams)
      ? buildPath(endpointRequest.path, endpointRequest.queryParams)
      : endpointRequest.path

    // add headers
    if (!isEmpty(endpointRequest.headers)) {
      for (var attrname in endpointRequest.headers) {
        request.headers[attrname] = endpointRequest.headers[attrname]
      }
    }

    // add the request body's content length
    if (!isEmpty(endpointRequest.body)) {
      body = JSON.stringify(endpointRequest.body)
      request.headers['Content-Length'] = Buffer.byteLength(body)
      request.headers['Content-Type'] = 'application/json'
    }

    // if maxsockets where provided use the apropriate agent
    if (maxSockets) {
      request.agent = endpointRequest.test === true ? httpAgent : httpsAgent
    }
    return request
  }

  // API is the main interface to the API.
  this.API = function (endpointRequest, callback) {
    var request = buildRequest(globalRequest, endpointRequest)

    var requestProtocol = null;

    if (endpointRequest.test === true) {
      requestProtocol = http
      request.port = endpointRequest.port
    } else {
      requestProtocol = https
    }

    var httpRequest = requestProtocol.request(request, function (httpResponse) {
      var responseBody = ''

      // cature the response from the API
      httpResponse.on('data', function (chunk) {
        responseBody += chunk
      })

      // after the call is complete, build the response object
      httpResponse.on('end', function () {
        var response = JSON.parse(JSON.stringify(emptyResponse))
        response.statusCode = httpResponse.statusCode
        response.body = responseBody
        response.headers = httpResponse.headers
        callback(response)
      })
    })

    httpRequest.on('error', function (e) {
      var response = JSON.parse(JSON.stringify(emptyResponse))
      response.statusCode = e.statusCode || 500
      response.body = JSON.stringify({
        message: e.message,
        name: e.name,
        stack: e.stack
      })
      callback(response)
    })

    // if thre is a request body, sent it
    if (!isEmpty(endpointRequest.body)) {
      httpRequest.write(body)
    }

    httpRequest.end()
  }

  return this
}
997633
function _websocketPort(ctx, port) {
  const forwarded = ctx.header['x-forwarded-proto'];
  const protocol = forwarded ? forwarded.split(',')[0] : undefined;
  return protocol === 'https' ? 443 : port;
}
1042851
function Channel_connect(cb) {
  cb = utils.callOnce(cb)

  var wsClient = new websocket.client()

  wsClient.addListener("connect",       onConnect)
  wsClient.addListener("connectFailed", onConnectFailed)

  wsClient.connect(this._url, [this._protocol])

  var channel = this

  //-----------------------------------
  function onConnect(wsConn) {
    channel._wsConn = wsConn

    wsConn.addListener("message", onMessage)
    wsConn.addListener("close",   onClose)
    wsConn.addListener("error",   onError)

    cb(null)
  }

  //-----------------------------------
  function onConnectFailed(err) {
    cb(err)
  }

  //-----------------------------------
  function onMessage(message) {
    if (!channel._wsConn) return
    if (message.type != "utf8") return

    message = JSON.parse(message.utf8Data)
    DEBUGMSG("onMessage", utils.JL(message))

    channel.emit("message", message)
  }

  //-----------------------------------
  function onClose() {
    if (!channel._wsConn) return

    channel._wsConn = null
    channel.emit("close")
  }

  //-----------------------------------
  function onError(err) {
    channel.emit("error", err)
  }
}
1006111
def preview():  # pragma: no coverage
    """"""
    Handler = http.server.SimpleHTTPRequestHandler
    socketserver.TCPServer.allow_reuse_address = True
    port = CONFIG['http_port']
    httpd = socketserver.TCPServer(("", port), Handler)
    os.chdir(CONFIG['output_to'])
    try:
        logger.info("and ready to test at "
                    "http://127.0.0.1:%d" % CONFIG['http_port'])
        logger.info("Hit Ctrl+C to exit")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.shutdown()
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
1238046
function setupCommunications() {
  // Initiate a connection to the background page that we can use as a
  // channel for settings saving/etc.
  var port = chrome.extension.connect({
    name: 'injector'
  });

  // Listen for data from the extension.
  port.onMessage.addListener(function(data, port) {
    // We try to keep the data opaque so we don't waste any time here.
    sendMessage(data);
  });

  // Setup a communication channel with the page via events.
  var localId = String(Number(Date.now()));
  window.addEventListener('message', function(e) {
    // The message here is from the wtf.ipc.MessageChannel, and has some header
    // data in it.
    // Note that because we are also sending messages it's possible to get
    // our own messages back, so filter that by localId.
    var packet = e.data;
    if (!packet ||
        !packet['wtf_ipc_connect_token'] ||
        packet['wtf_ipc_sender_token'] == localId) {
      return;
    }
    var data = packet['data'];

    e.stopPropagation();

    // NOTE: Chrome ports do not support transferrables! Need to convert!

    // Pass through the messages.
    // We trust the Chrome security model and just send the data along.
    port.postMessage(data);
  }, false);

  function sendMessage(data) {
    var packet = {
      'wtf_ipc_connect_token': true,
      'wtf_ipc_sender_token': localId,
      'data': data
    };
    window.postMessage(packet, '*');
  };
}