Called when a client opens a websocket connection
546647
def onConnect(self, request):
        
        logger.debug("Connection opened ({peer})".format(peer=self.peer))

        self.storage = {}
        self._client_id = str(uuid1())
270051
function controlChannelRequest(server, message) {
  var address = message.request.address;
  var req = { headers: {} };
  var headers = [];

  // handler to call when the connection sequence completes
  var self = server;
  
  if ( message.request.method) {
    req = new IncomingMessage(message, server.controlChannel);
    if ( message.request.body == true) {
       self.pendingRequest = req;
    } else {
      req.push(null);
    }
  }
  
  // execute the web socket rendezvous with the server
  try {
    var client = new WebSocket(address, {
      headers: headers,
      perMessageDeflate: false
    });
    client.on('open', function() {
      
      server.emit('requestchannel', client);
      if (self.options.clientTracking) {
        self.clients.push(client);
        ws.on('close', function() {
          var index = self.clients.indexOf(client);
          if (index != -1) {
            self.clients.splice(index, 1);
          }
        });
      }

      // do we have a request or is this just rendezvous?
      if ( message.request.method) {
         var res = new ServerResponse(req);
         res.requestId = message.request.id;
         res.assignSocket(client);
         server.emit('request', req, res);
      }
    });

    client.on('error', function(event) {
      var index = server.clients.indexOf(client);
      if (index != -1) {
        server.clients.splice(index, 1);
      }
    });

  } catch (err) {
    console.log(err);
  }
}
675127
function Client(rwStream, options)
{
	events.EventEmitter.call(this);
	
	var tidCounter = 0;
	var requestMap = {};
	var isClosed = true;
	var address = '';
	var host = '';
	
	var idlePingTimeout 	= getOption(options, 'idlePingTimeout',		0);
	var idleCloseTimeout	= getOption(options, 'idleCloseTimeout',	0);
	var autoRegister		= getOption(options, 'autoRegister', 		false);
	var logConnection		= getOption(options, 'logConnection', 		true);
	var autoResponseUnhandledCommand = getOption(options, 'autoResponseUnhandledCommand', true);
	
	this.isServer = options.isServer;
	
	function getAddress()
	{
		return util.format('%s:%s', rwStream.remoteAddress.replace(/^::ffff:/i, ''), rwStream.remotePort);		
	}
	
	function log(event)
	{
		if ( logConnection )
		{
			console.log(util.format('%s %s(%s)', event, host, address));
		}
	}
	
	this.closeStream = function() {

		//console.log('isClosed ' + isClosed);
		
		if ( !isClosed )
		{
			isClosed = true;
			
			log('CLOSE');
			
			if ( rwStream instanceof stream.Writable )
			{
				rwStream.end();
			}
		
			for ( var tid in requestMap )
			{
				if ( requestMap.hasOwnProperty(tid) )
				{
					clearTimeout(requestMap[tid].timer);
					requestMap[tid].callback({code: '500', tid: tid, args: ['socket_closed'], body: null, isValid: true});
					delete requestMap[tid];
				}
			}
			
			this.emit('close');
		}
	};
	
	if ( rwStream instanceof stream.Writable )
	{
		this.sendMessage = function(code, tid, args, body, callback) {
			var bodyBuf = Buffer.isBuffer(body) ? body : 
				typeof(body) === 'string' ? Buffer.from(body) : 
					null;
			tid = tid === -1 ? ++tidCounter : tid;
			tid = '' + tid;
			var bodyLen = bodyBuf ? bodyBuf.length : 0;
			var header = util.format('%s %s %d%s\r\n', code, tid, bodyLen, encodeArgs(args));
			var headerLen = Buffer.byteLength(header);
			var msg = {code: code, tid: tid, args: args, body: body};
			if ( options.debugHeader )
			{
				console.log("send msg: %s", msg2str(msg));
			}
			rwStream.write(header, callback);
			if ( bodyLen > 0 )
			{
				rwStream.write(bodyBuf);
			}
		};

		this.sendRequest = function(code, args, body, timeout, callback) {
			var tid = ++tidCounter;
			this.sendMessage(code, tid, args, body);
			requestMap[tid] = {
				callback: callback,
				timer: setTimeout(() => this.emit('message_timeout', tid), timeout)
			};
		};
	}
	
	if ( rwStream instanceof stream.Readable )
	{
		var parser = textParser.createParser((msg) => {

			if ( options.debugHeader )
			{
				console.log("recv msg: %s", msg2str(msg));
			}

			if ( !msg.isValid && this.sendMessage )
			{
				this.sendMessage('201', 0, 'invalid_command');
			}
			else
			{
				if ( /^\d+$/.test(msg.code) )
				{
					var tid = msg.tid !== null && /^\d+$/.test(msg.tid) ? msg.tid * 1 : 0;
					
					if ( tid > 0 )
					{
						if ( requestMap.hasOwnProperty(msg.tid) )
						{
							clearTimeout(requestMap[msg.tid].timer);
							requestMap[msg.tid].callback(msg);
							delete requestMap[msg.tid];
						}
						else
						{
							console.log(util.format('ERR dangling response: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
						}
					}
					else
					{
						console.log(util.format('ERR invalid tid: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
					}
				}
				else
				{
					var isHandled = false;
					
					if ( this.listenerCount(msg.code) > 0 )
					{
						isHandled = true;
						this.emit(msg.code, msg);
					}
					
					if ( this.listenerCount('message') > 0 )
					{
						isHandled = true;
						this.emit('message', msg);
					} 
					
					if ( !isHandled && autoResponseUnhandledCommand && this.sendMessage )
					{
						this.sendMessage('201', msg.tid, 'unknown_command');
					}
				}
			}
		});
		
		rwStream.on('data', (data) => {
			parser.feed(data);
		});
		
		rwStream.on('end', (e) => {
			this.closeStream();
		});
	}
	
	if ( rwStream instanceof net.Socket )
	{
		if ( !rwStream.connecting )
		{
			this.address = address = getAddress();
			isClosed = false;
			log('ACCEPT');
		}

		if ( idlePingTimeout > 0 )
		{
			rwStream.setTimeout(idlePingTimeout);
		}
		else if ( idleCloseTimeout > 0 )
		{
			rwStream.setTimeout(idleCloseTimeout);
		}
		
		rwStream.on('timeout', () => {
			if ( idlePingTimeout > 0 )
			{
				this.sendMessage('PING', 0, [], null);
				log('PING');
			}
			else if ( idleCloseTimeout > 0 )
			{
				this.closeStream();
			}
			else
			{
				this.emit('timeout');
			}
		});
		
		rwStream.on('connect', () => {
			this.address = address = getAddress();
			isClosed = false;
			log('CONNECT');
			if ( autoRegister )
			{
				this.sendMessage('RGST', 0, os.hostname());
				log('RGST');
			}
			this.emit('connect');
		});
		
		rwStream.on('close', (had_error) => {
			this.closeStream();
		});
		
		this._getSessionManager = function() {
			if ( !this.sessionManager )
			{
				this.sessionManager = new SessionManager(this, options);
			}
			return this.sessionManager;
		};
		
		this.onSession = function(protocol, callback) {
			var smgr = this._getSessionManager();
			var listener_options = Object.assign({}, options, {protocol: protocol});
			var slnr = new SessionListener(listener_options);
			slnr.on('session', callback);
			smgr.registerListener(slnr);
		};
		
		this.createSession = function(protocol, session_args) {
			var smgr = this._getSessionManager();
			var session_options = Object.assign({}, options, {protocol: protocol, session_args: session_args});
			return smgr.createSession(session_options);
		};
	} 
	
	rwStream.on('error', (e) => {
		log('ERROR ' + e.message);
		this.closeStream();
		this.emit('error', e);
	});
	
	this.on('message_timeout', (tid) => {
		if ( requestMap.hasOwnProperty(tid) )
		{
			requestMap[tid].callback({code: '500', tid: tid, args:['message_timeout'], body: null, isValid: true});
			delete requestMap[tid];
		}
	});
	
	this.on('RGST', (msg) => {
		host = msg.args.length > 0 ? msg.args[0] : '';
		log('RGST');
	});
	
	this.on('PING', (msg) => {
		log('PING');
	});
}
314541
def on_open(self):
        
        def event_loop():
            logger.debug(pformat(self.query.request))
            self.send(json.dumps(self.query.request))
            while not self.event.is_set():
                #print('Waiting around on the socket: %s' % self.gettimeout())
                self.event.wait(self.gettimeout())
                
            logger.debug('Event loop terminating.')
    
        self.thread = threading.Thread(
            target=event_loop)
        self.thread.setDaemon(True)
        self.thread.start()
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
648290
def on_message(self, message):
        
        log.debug('Got websocket message %s', message)
        if message == 'websocket client ready':
            if self.connected:
                # TBD: Add ability to run commands in this branch
                log.debug('Websocket already connected, returning')
                return

            self.connected = True

            evt_processor = event_processor.SaltInfo(self)
            client = salt.netapi.NetapiClient(self.application.opts)
            client.run({
                'fun': 'grains.items',
                'tgt': '*',
                'token': self.token,
                'mode': 'client',
                'asynchronous': 'local_async',
                'client': 'local'
                })
            while True:
                try:
                    event = yield self.application.event_listener.get_event(self)
                    evt_processor.process(event, self.token, self.application.opts)
                    # self.write_message('data: {0}\n\n'.format(salt.utils.json.dumps(event, _json_module=_json)))
                except Exception as err:
                    log.debug('Error! Ending server side websocket connection. Reason = %s', err)
                    break

            self.close()
        else:
            # TBD: Add logic to run salt commands here
            pass
663318
function() {
        Strophe.info("Websocket open");
        var start = this._buildStream();
        this._conn.xmlOutput(start.tree());

        var startString = Strophe.serialize(start);
        this._conn.rawOutput(startString);
        this.socket.send(startString);
    }
36279
function () {
        // Ensure that there is no open WebSocket from a previous Connection.
        this._closeSocket();

        // Create the new WobSocket
        this.socket = new WebSocket(this._conn.service, "xmpp");
        this.socket.onopen = this._onOpen.bind(this);
        this.socket.onerror = this._onError.bind(this);
        this.socket.onclose = this._onClose.bind(this);
        this.socket.onmessage = this._connect_cb_wrapper.bind(this);
    }
1184505
async def open_websocket(url: str,
                         headers: Optional[list] = None,
                         subprotocols: Optional[list] = None):
    
    ws = await create_websocket(
        url, headers=headers, subprotocols=subprotocols)
    try:
        yield ws
    finally:
        await ws.close()
334952
function connect()
    {
        if(scope._conn)
        {
            if(scope._conn.readyState === 1)
            {
                return;
            }
            scope._conn.close();
        }
        var url = (scope._redirectURL.length>0) ? scope._redirectURL : scope._url;

        scope._conn            = new WebSocket(url);
        scope._conn.binaryType = "arraybuffer";
        scope._conn.open       = onOpen;
        scope._conn.onerror    = onerror;
        scope._conn.onclose    = onClose;
        scope._conn.onmessage  = onMessage;
    }
23103
async def handler(self):
    ''''''
    self.ws = await websockets.connect(self.url, ssl=self.ssl)
    while self.ws:
      message = await self.ws.recv()
      for handle in self.on_message:
        if asyncio.iscoroutinefunction(handle):
          await handle(self, message)
        else:
          handle(self, message)
226576
def on_message(self, message):
        
        log.debug('Got websocket message %s', message)
        if message == 'websocket client ready':
            if self.connected:
                # TBD: Add ability to run commands in this branch
                log.debug('Websocket already connected, returning')
                return

            self.connected = True

            while True:
                try:
                    event = yield self.application.event_listener.get_event(self)
                    self.write_message(
                        salt.utils.json.dumps(event, _json_module=_json))
                except Exception as err:
                    log.info('Error! Ending server side websocket connection. Reason = %s', err)
                    break

            self.close()
        else:
            # TBD: Add logic to run salt commands here
            pass
587120
def _on_error(self, websock, e):
        '''
        
        '''
        if isinstance(e, (
            websocket.WebSocketConnectionClosedException,
            ConnectionResetError)):
            self.logger.error('websocket closed, did chrome die?')
        else:
            self.logger.error(
                    'exception from websocket receiver thread',
                    exc_info=1)
        brozzler.thread_raise(self.calling_thread, BrowsingException)
170921
function() {
        try {
          if (socket && socket.readyState == 1) {
            return;
          }

          socket = new WebSocket(address, []);

          socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
          socketRealTimeStatusInterval = setInterval(function() {
            switch (socket.readyState) {
              case 2:
                onCloseHandler(null);
                break;
              case 3:
                socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
                break;
            }
          }, 5000);

          socket.onopen = function(event) {
            waitForSocketToConnect(function() {
              eventCallback["open"]();
            });
          }

          socket.onmessage = function(event) {
            var messageData = JSON.parse(event.data);
            eventCallback["message"](messageData);

            /**
             * To avoid manually closing socket's connection
             */
            forceCloseSocket = false;

            socketCloseTimeout && clearTimeout(socketCloseTimeout);
            forceCloseTimeout && clearTimeout(forceCloseTimeout);

            socketCloseTimeout = setTimeout(function() {
              /**
               * If message's type is not 5, socket won't get any acknowledge packet,therefore
               * you may think that connection has been closed and you would force socket
               * to close, but before that you should make sure that connection is actually closed!
               * for that, you must send a ping message and if that message don't get any
               * responses too, you are allowed to manually kill socket connection.
               */
              ping();

              /**
               * We set forceCloseSocket as true so that if your ping's response don't make it
               * you close your socket
               */
              forceCloseSocket = true;

              /**
               * If type of messages are not 5, you won't get ant ACK packets
               * for that being said, we send a ping message to be sure of
               * socket connection's state. The ping message should have an
               * ACK, if not, you're allowed to close your socket after
               * 4 * [connectionCheckTimeout] seconds
               */
              forceCloseTimeout = setTimeout(function() {
                if (forceCloseSocket) {
                  socket.close();
                }
              }, connectionCheckTimeout);

            }, connectionCheckTimeout * 1.5);
          }

          socket.onclose = function(event) {
            onCloseHandler(event);
          }

          socket.onerror = function(event) {
            eventCallback["error"](event);
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4000,
            errorMessage: "ERROR in WEBSOCKET!",
            errorEvent: error
          });
        }
      }
389877
@Override
  public void onClosing(WebSocket webSocket, int code, String reason) {
    socketOpen = false;
    callback.onDisconnected();
  }
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
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)