WebSocketClientMonitor interfaces
324830
public void onOpen() {
    LOGGER.d("webSocket established...");
    connectionEstablished = true;
    retryConnectionCount = 0;
    for (AVConnectionListener listener: connectionListeners.values()) {
      listener.onWebSocketOpen();
    }

    resetConnectingStatus(true);

    // auto send login packet.
    LoginPacket lp = new LoginPacket();
    lp.setAppId(AVOSCloud.getApplicationId());
    lp.setInstallationId(AVInstallation.getCurrentInstallation().getInstallationId());
    this.sendPacket(lp);
  }
668483
function(host, port) {
  var sock = new WebSocket('ws://' + host + ':' + port);
  sock.onopen = function() {
    console.log("Connected to browserify-reload handle");
  }

  sock.onmessage = function(msg){
    if(msg && msg.data == "reload")
      document.location = document.location.href;
  }
}
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
1004779
function clientNetworkData(channelDefArray, opt) {
	var self = {
		__TYPE__ : MessageType.CS_NET,
		channelCount : new type.UInt32Le( function () {
			return self.channelDefArray.obj.length;
		}),
		channelDefArray : channelDefArray || new type.Factory( function (s) {
			self.channelDefArray = new type.Component([]);
			
			for (var i = 0; i < self.channelCount.value; i++) {
				self.channelDefArray.obj.push(channelDef().read(s));
			}
		})
	};
	
	return new type.Component(self, opt);
}
1276138
private void createMonitor(LinkListener l) throws KNXException
	{
		final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium");
		if (options.containsKey("serial")) {
			final String p = (String) options.get("serial");
			try {
				m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium);
			}
			catch (final NumberFormatException e) {
				m = new KNXNetworkMonitorFT12(p, medium);
			}
		}
		else {
			// create local and remote socket address for monitor link
			final InetSocketAddress local = createLocalSocket((InetAddress) options
				.get("localhost"), (Integer) options.get("localport"));
			final InetSocketAddress host = new InetSocketAddress((InetAddress) options
				.get("host"), ((Integer) options.get("port")).intValue());
			// create the monitor link, based on the KNXnet/IP protocol
			// specify whether network address translation shall be used,
			// and tell the physical medium of the KNX network
			m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium);
		}
		// add the log writer for monitor log events
		LogManager.getManager().addWriter(m.getName(), w);
		// on console we want to have all possible information, so enable
		// decoding of a received raw frame by the monitor link
		m.setDecodeRawFrames(true);
		// listen to monitor link events
		m.addMonitorListener(l);
		// we always need a link closed notification (even with user supplied listener)
		m.addMonitorListener(new LinkListener() {
			public void indication(FrameEvent e)
			{}

			public void linkClosed(CloseEvent e)
			{
				System.out.println("network monitor exit, " + e.getReason());
				synchronized (NetworkMonitor.this) {
					NetworkMonitor.this.notify();
				}
			}
		});
	}
1326377
private <T extends Rdp4jListener> void notifyListeners(Class<T> listenerType, Notifier<T> notifier)
            throws InterruptedException {
        for (Rdp4jListener listener : listeners) {
            if (isInstanceOf(listener, listenerType)) {
                /*
                 * This cast is correct, since we check if listener
                 * is instance of listenerType.
                 */
                @SuppressWarnings("unchecked")
                T listener2 = (T) listener;
                try {
                    notifier.notify(listener2);
                } catch (InterruptedException e) {
                    throw e;
                } catch (Throwable e) {
                    logErrorMessage(e);
                }
            }
        }
    }
554362
def lookupListener(self, listenID):
        
        if listenID in self.inboundConnections:
            # Make the connection?
            cwait, call = self.inboundConnections.pop(listenID)
            # _ConnectionWaiter instance
            call.cancel()
            return cwait
87552
private void initializeStream(URI uri, Token token, long sessionIdleTimeout, long idleTimeout)
            throws SaltException {
        try {
            URI adjustedURI = new URI(uri.getScheme() == "https" ? "wss" : "ws",
                    uri.getSchemeSpecificPart(), uri.getFragment())
                    .resolve("ws/" + token.getToken());
            websocketContainer.setDefaultMaxSessionIdleTimeout(sessionIdleTimeout);

            // Initiate the websocket handshake
            synchronized (websocketContainer) {
                session = websocketContainer.connectToServer(this, adjustedURI);
                session.setMaxIdleTimeout(idleTimeout);
            }
        } catch (URISyntaxException | DeploymentException | IOException e) {
            throw new SaltException(e);
        }
    }
535094
private void initWebClientConfig() {
        m_webClientConfig = new WebClientConfiguration();

        if (getParameter("httpClientTimeoutSecs") != null)
            m_webClientConfig.setTimeoutSecs(Integer.parseInt(getParameter("httpClientTimeoutSecs")));

        if (getParameter("httpClientSocketTimeoutSecs") != null)
            m_webClientConfig.setSockTimeoutSecs(Integer.parseInt(getParameter("httpClientSocketTimeoutSecs")));

        if (getParameter("httpClientMaxConnectionsPerHost") != null)
            m_webClientConfig.setMaxConnPerHost(Integer.parseInt(getParameter("httpClientMaxConnectionsPerHost")));

        if (getParameter("httpClientMaxTotalConnections") != null)
            m_webClientConfig.setMaxTotalConn(Integer.parseInt(getParameter("httpClientMaxTotalConnections")));

        if (getParameter("httpClientFollowRedirects") != null)
            m_webClientConfig.setFollowRedirects(Boolean.parseBoolean(getParameter("httpClientFollowRedirects")));

        if (getParameter("httpClientMaxFollowRedirects") != null)
            m_webClientConfig.setMaxRedirects(Integer.parseInt(getParameter("httpClientMaxFollowRedirects")));

        if (getParameter("httpClientUserAgent") != null)
            m_webClientConfig.setUserAgent(getParameter("httpClientUserAgent"));
    }
1046356
def network_io_counters(interface=None):
    '''
    
    '''
    if not interface:
        return dict(psutil.net_io_counters()._asdict())
    else:
        stats = psutil.net_io_counters(pernic=True)
        if interface in stats:
            return dict(stats[interface]._asdict())
        else:
            return False
1049020
function gattServerCallbackHandler(winFunc, settings) {
	// collect read/write callbacks and add handles, so the native side can tell us which one to call.
	var readCallbacks = {};
	var writeCallbacks = {};
	var nextHandle = 1;

	function handleCallback(object, name, callbacks) {
		if(!object[name]) {
			throw name+" missing!";
		}
		callbacks[nextHandle] = object[name];
		object[name+"Handle"] = nextHandle;
		nextHandle += 1;
	}

	function handleReadWrite(object) {
		/* // primitive version
		if(!object.readRequestCallback) {
			throw "readRequestCallback missing!");
		}
		readCallbacks[nextHandle] = object.readRequestCallback;
		*/
		handleCallback(object, "onReadRequest", readCallbacks);
		handleCallback(object, "onWriteRequest", writeCallbacks);
	}

	for(var i=0; i<settings.services.length; i++) {
		var service = settings.services[i];
		for(var j=0; j<service.characteristics.length; j++) {
			var characteristic = service.characteristics[j];
			handleReadWrite(characteristic);
			for(var k=0; k<characteristic.descriptors.length; k++) {
				var descriptor = characteristic.descriptors[k];
				handleReadWrite(descriptor);
			}
		}
	}

	settings.nextHandle = nextHandle;

	return function(args) {
		// primitive version
		/*if(args.name == "win") {
			winFunc();
			return;
		}*/
		var funcs = {
			win: winFunc,
			connection: function() {
				settings.onConnectionStateChange(args.deviceHandle, args.connected);
			},
			write: function() {
				writeCallbacks[args.callbackHandle](args.deviceHandle, args.requestId, args.data);
			},
			read: function() {
				readCallbacks[args.callbackHandle](args.deviceHandle, args.requestId);
			},
		};
		funcs[args.name]();
	};
}
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 []
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
800169
function(self, agent, msg, cb) {
  logger.debug('[%s] receive addServer signal: %j', self.app.serverId, msg);
  if(!msg || !msg.server) {
    logger.warn('monitorwatcher addServer receive empty message: %j', msg);
    utils.invokeCallback(cb, Constants.SIGNAL.FAIL);
    return;
  }
  addServers(self, [msg.server]);
  utils.invokeCallback(cb, Constants.SIGNAL.OK);
}
303808
function OnvifManager() {
	this.ws = null; // WebSocket object
	this.el = { // jQuery objects for the HTML elements
		'frm_con' : $('#connect-form'),
		'sel_dev' : $('#connect-form select[name="device"]'),
		'inp_usr' : $('#connect-form input[name="user"]'),
		'inp_pas' : $('#connect-form input[name="pass"]'),
		'btn_con' : $('#connect-form button[name="connect"]'),
		'div_pnl' : $('#connected-device'),
		'img_snp' : $('#connected-device img.snapshot'),
		'btn_dcn' : $('#connected-device button[name="disconnect"]'),
		'mdl_msg' : $('#message-modal'),
		'ptz_spd' : $('input[name="ptz-speed"]'),
		'btn_hme' : $('#connected-device div.ptz-pad-box button.ptz-goto-home'),
		'ptz_pad' : $('#connected-device div.ptz-pad-box'),
		'zom_in'  : $('#connected-device div.ptz-zom-ctl-box button.ptz-zom-in'),
		'zom_out' : $('#connected-device div.ptz-zom-ctl-box button.ptz-zom-ot'),
	};
	this.selected_address = '';
	this.device_connected = false;
	this.ptz_moving = false;
	this.snapshot_w = 400;
	this.snapshot_h = 300;
}
1290277
public static synchronized void websocket(String url, AbstractReceiveListener endpoint) {
        checkStarted();
        instance().endpoints.add(HandlerUtil.websocket(url, endpoint));
    }
805019
function DevAdapter (controller) {
    this.id        = controller.svc;
    this.uid       = "//" + controller.svcopts.adapter + "/" + controller.svc + ":" +  controller.svcopts.port;;
    this.id        = controller.svcopts.adapter;
    this.info      = 'websock';
    this.control   = 'websock';                // this wait for clients to connect via websock  
    this.debug     =  controller.svcopts.debug; // inherit debug from controller
    this.src       =  controller.svcopts.src || controller.svcopts.port; // websock serial id for HTML clients
    this.controller =  controller;               // keep a link to device controller and TCP socket
    this.clients   =  [];                      // array to keep track of client
    this.count     =  0;                       // index for incomming client
    this.Debug (1,"uid=%s", this.uid);    

    HookBackendEvent(this, controller.gateway.backend);
}