a relay WS server(on the main server side), help communicate bettwen main server and local/debug serverf
165561
function init(options){
	options = util._extend({ssl:null, port:12345}, options);
	var serverWorkers = {}; // save main server sockets
	var clientSocket = []; // save local server socket
	var clientOptions = []; // save optioin obj
	var wsServer;
	if(options.ssl)
		wsServer = require('https').createServer(options.ssl);
	else wsServer = require('http').createServer();
	var io = require('socket.io')(wsServer);
	
	if(options.auth)	
	io.set('authorization', function (handshakeData, callback) {
		if(handshakeData.url.match('username='+options.auth.username+'&password='+options.auth.password))
        	callback(null, true); // error first callback style 
        else callback('no auth', false);
    });

	io.on('connection', function(socket){
		// 0. save server sockets & local socket
		socket.on('init', function(data){
			if(data._type == 'localServer'){
				socket._type = 'localServer';
				if(clientSocket.length>0)
					clientSocket.slice(-1)[0].emit('hold');			
				// then handle new one
				clientSocket.push(socket);
				clientOptions.push(data);
				// inform server the new client
				for(i in serverWorkers)
					serverWorkers[i].emit('client', data);
			}else if(data._type == 'server'){
				socket._type = 'server';
				serverWorkers[socket.id] = socket;
			}else{
				// ignore this connection
			}
		})
		// handle req from server, relay data to client
		socket.on('req', function(data){
			if(clientSocket.length > 0){
				data._sid = socket.id;
				clientSocket.slice(-1)[0].emit('req', data)
			}
		})
		// handle res from client, relay the data to the server
		socket.on('res', function(data){
			if(serverWorkers[data._sid])
				serverWorkers[data._sid].emit('res', data);
		});
		socket.on('disconnect', function(reason){
			if(socket._type == 'localServer'){
				var last = false;
				for(i in clientSocket){
					if(socket.id == clientSocket[i].id){
						if(i == clientSocket.length-1)
							last = true;
						clientSocket.splice(i, 1);
						clientOptions.splice(i,1);
						break;
					}
				}
				if(clientSocket.length > 0 && clientOptions.length > 0){
					if(last)
						clientSocket.slice(-1)[0].emit('back');	
					for(i in serverWorkers)
						serverWorkers[i].emit('client', clientOptions.slice(-1)[0]);
				}
				else
					for(i in serverWorkers)
						serverWorkers[i].emit('client', false);
			}
			else if(socket._type == 'server')
				delete serverWorkers[socket.id];
		});
	});
	wsServer.listen(options.port).on('listening', function(){
		options.listening ? options.listening() : noop();
		//console.log('[NLT] Server is ready on port ' + options.port);
	}).on('error', function(e){
		options.error ? options.error(e) : noop();
		//console.log('[NLT] Setup error', e)
	});
}
125401
function tail (argv, callback) {
  if (!argv[2]) {
    console.error('url is required')
    console.error('Usage : tail <url>')
    process.exit(-1)
  }
  var uri = argv[2]
  var wss = 'wss://' + uri.split('/')[2] + '/'

  var s = new ws(wss, {
    origin: 'http://websocket.org'
  })

  s.on('open', function open () {
    s.send('sub ' + uri)
  })

  s.on('close', function close () {
    console.log('disconnected')
  })

  s.on('message', function message (data, flags) {
    var a = data.split(' ')
    if (a.length && a[0] === 'pub') {
      util.get(a[1], function (err, res) {
        if (err) {
          console.error('Error : ' + err)
        } else {
          console.log(res)
        }
      })
    }
  })
}
866860
public static void main(String[] args) throws Exception {

    AuthClient client = new AuthClient("localhost", 50051);
    try {
      /* Access a service running on the local machine on port 50051 */
      String user = "world";
      if (args.length > 0) {
        user = args[0]; /* Use the arg as the name to greet if provided */
      }
      if (args.length > 1) {
        client.setTokenValue(args[1]);
      }
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
126407
function serverInitMessage(
  batfishConfig: BatfishConfiguration,
  actualPort: number
): string {
  const localUrl = joinUrlParts(
    `http://localhost:${actualPort}`,
    batfishConfig.siteBasePath,
    ''
  );
  const chevron = chalk.green.bold('>');
  let result = `Development server ready.`;
  result += `\n  ${chevron} Access your site at ${chalk.bold.magenta.underline(
    localUrl
  )}`;

  const ip = address.ip();
  if (ip) {
    const externalUrl = joinUrlParts(
      `http://${ip}:${actualPort}`,
      batfishConfig.siteBasePath,
      ''
    );
    result += `\n  ${chevron} Available externally at ${chalk.magenta(
      externalUrl
    )}`;
  }

  result += `\n  ${chevron} Compiled files are in ${chalk.cyan(
    path.relative(process.cwd(), batfishConfig.outputDirectory)
  )}`;
  return result;
}
378215
function startRecorderServer(config, onReady, onCommand, onEnd){
    var server = http.createServer(function(req, res){
        if(req.url === '/proxy.pac'){
            var wdproxy = config.wdproxy;
            if(wdproxy){
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                var pacContent = 'function FindProxyForURL(url, host){if(!/^(127.0.0.1|localhost)$/.test(host))return "PROXY '+config.wdproxy+'";\r\nreturn "DIRECT"}';
                res.end(pacContent);
            }
            else{
                res.end('No wdproxy finded!');
            }
        }
    });
    server.listen(0, function(){
        var serverPort = server.address().port;
        console.log('');
        console.log(__('recorder_server_listen_on').green, serverPort);
        onReady(serverPort);
    });
    wsServer = new WebSocketServer({
        httpServer: server,
        autoAcceptConnections: true
    });
    wsServer.on('connect', function(connection) {
        wsConnection = connection;
        sendWsMessage('config', config);
        connection.on('message', function(message) {
            var message = message.utf8Data;
            try{
                message = JSON.parse(message);
            }
            catch(e){};
            var type = message.type;
            switch(type){
                case 'saveCmd':
                    onCommand(message.data);
                    break;
                case 'save':
                    onCommand({
                        cmd: 'end'
                    });
                    setTimeout(function(){
                        wsConnection && wsConnection.close();
                        server.close(function(){
                            onEnd(true);
                        });
                    }, 500);
                    break;
                case 'end':
                    onCommand({
                        cmd: 'end'
                    });
                    setTimeout(function(){
                        wsConnection && wsConnection.close();
                        server.close(function(){
                            onEnd(false);
                        });
                    }, 500);
                    break;
            }
        });
        connection.on('close', function(reasonCode, description) {
            wsConnection = null;
        });
    });
}
174688
function sub (subURI, callback) {
  var PING_TIMEOUT = process.env['PING_TIMEOUT']

  if (!subURI) {
    callback(new Error('uri is required'))
    return
  }
  var domain = subURI.split('/')[2]
  var wss = 'wss://' + domain + '/'

  var Socket = new ws(wss, {
    origin: 'http://websocket.org'
  })

  Socket.on('open', function open () {
    debug('connected')
    Socket.send('sub ' + subURI)

    if (PING_TIMEOUT && parseInt(PING_TIMEOUT) && parseInt(PING_TIMEOUT) > 0 ) {
      setInterval(function() {
        debug('sending ping')
        Socket.send('ping')
      }, parseInt(PING_TIMEOUT * 1000))
    }

  })

  Socket.on('close', function close () {
    debug('disconnected')
  })

  Socket.on('message', function message (data, flags) {
    debug(data)
    callback(null, data)
  })
}
22980
function server() {
  // TODO: Show require express error
  var express = require('express')
    , app = express();

  app.configure(function() {
    app.use(express.static(siteBuilder.outputRoot));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  // Map missing trailing slashes for posts
  app.get('*', function(req, res) {
    var postPath = siteBuilder.outputRoot + req.url + '/';
    // TODO: Security
    if (req.url.match(/[^/]$/) && existsSync(postPath)) {
      res.redirect(req.url + '/');
    } else {
      res.send('404');
    }
  });

  app.listen(siteBuilder.config.port);
  log.info('Listening on port', siteBuilder.config.port);
}
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);
    }

}
905111
def _start_remote_debugging(port):
  """"""
  try:
    print("Connecting to remote debugger on localhost:{}.".format(port))
    import pydevd  # pylint: disable=g-import-not-at-top
    pydevd.settrace(
        "localhost",
        port=port,
        stdoutToServer=True,
        stderrToServer=True,
        suspend=flags.FLAGS.break_on_start)
  except ImportError:
    print(
        "pydevd is required for remote debugging. Please follow the PyCharm"
        "manual or run `pip install pydevd-pycharm` to install.",
        file=sys.stderr)
636690
protected function connectWs()
	{
		$wsUrl = sprintf('ws://%s/v1/clients/%s/ws', $this->serverUrl, $this->getId());

		$this->ws = new WebsocketClient($wsUrl, ['timeout' => 30]);
		$this->ws->setTimeout(30);
	}
120408
function ESP8266IoT(debug){
	that = this;
	that.options = {'button_URL':'/button','relay_URL':'/relay','modtcmk2_URL':'/mod-tc-mk2','fingerPrint_URL':"/mod-finger"};
	that.options.debug = debug ? debug : false;
	events.EventEmitter.call(this);
	that.connection;
	that.relayState = 0;
	if (that.options.debug == true) {
		console.log("Init Board...");
	};
	that.init();
}
1129750
function startServer(devServerUrl) {
  const { port: devServerPort } = url.parse(devServerUrl);
  return choosePort(HOST, devServerPort - 1)
    .then(port => {
      if (port == null) {
        // We have not found a port.
        return;
      }
      const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
      const appName = require(paths.appPackageJson).name;
      const urls = prepareUrls(protocol, HOST, port);
      // Directly set the HOST, PORT and PROTOCOL, which would be used in DefinePlugin
      // let the webpack define the public path correctly in DefinePlugin
      process.env.HOST = HOST;
      process.env.PORT = port;
      process.env.PROTOCOL = protocol;
      process.env.PUBLIC_URL = url.format({ protocol: protocol, hostname: HOST, port: devServerPort });

      // Create a webpack compiler that is configured with custom messages.
      const webpackConfig = serverlize(paths, config, `${devServerUrl}/`);
      const compiler = createCompiler(webpack, webpackConfig, appName, urls, useYarn);
      let browserOpened = false;
      compiler.watch({
        quiet: true,
        stats: 'none'
      }, (err, stats) => {
        if (!browserOpened) {
          openBrowser(urls.localUrlForBrowser);
          browserOpened = true;
        }
        if (err) {
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(err);
          return;
        }
        if (isInteractive) {
          clearConsole();
        }
        const messages = formatWebpackMessages(stats.toJson({}, true));
        if (messages.errors.length) {
          // Only keep the first error. Others are often indicative
          // of the same problem, but confuse the reader with noise.
          if (messages.errors.length > 1) {
            messages.errors.length = 1;
          }
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(new Error(messages.errors.join('\n\n')));
          return;
        }
        console.log(chalk.green('Compiled successfully!'));
        console.log(
          `To create a production build, use ` +
            `${chalk.cyan(`${useYarn ? 'yarn' : 'npm run'} build:server`)}.`
        );
        console.log('Note that all client side errors or warnings are suppressed.');
        console.log();
      });
    })
    .catch(err => {
      if (err && err.message) {
        console.log(err.message);
      }
      process.exit(1);
    });
}
1032122
def cli(wio):
    '''
    
    '''
    token = wio.config.get("token", None)
    mserver_url = wio.config.get("mserver", None)
    msvr_ip = wio.config.get("mserver_ip", None)
    if not mserver_url or not token:
        click.echo(click.style('>> ', fg='red') + "Please login, use " +
            click.style("wio login", fg='green'))
        return
    msvr = urlparse(mserver_url).hostname
    xsvr = msvr
    xsvr_ip = msvr_ip
    board = ''

    click.secho('> ', fg='green', nl=False)
    click.echo("Setup is easy! Let's get started...\n")
    click.secho('! ', fg='green', nl=False)
    click.echo("PROTIP: " +
        click.style("Hold the ", fg='white') +
        click.style("Configure ", fg='green') +
        click.style("button ~4s into Configure Mode!", fg='white'))
    click.secho('! ', fg='green', nl=False)
    click.echo("PROTIP: " +
        click.style("Please make sure you are ", fg='white') +
        click.style("connected ", fg='green') +
        click.style("to the ", fg='white') +
        click.style("Server", fg='green'))
    click.echo()
    click.secho('? ', fg='green', nl=False)
    if not click.confirm(click.style('Would you like continue?', bold=True), default=True):
        click.echo('Quit setup!')
        return

    ### choice board
    while 1:
        for x in range(len(boards)):
            click.echo("%s.) %s" %(x, boards[x]))
        click.secho('? ', fg='green', nl=False)
        value = click.prompt(click.style('Please choice the board type', bold=True), type=int)
        if value >= 0 and value < len(boards):
            board = boards[value]
            break
        else:
            click.echo(click.style('>> ', fg='red') + "invalid input.")

    r = get_new(mserver_url, token, board)
    if not r:
        return
    node_key = r["node_key"]
    node_sn = r["node_sn"]

    ### list wio with serial
    if board == WIO_LINK_V1_0:
        try:
            ports = serial_list.serial_ports()
        except serial.SerialException as e:
            click.secho('>> ', fg='red', nl=False)
            click.echo(e)
            if e.errno == 13:
                click.echo("For more information, see https://github.com/Seeed-Studio/wio-cli#serial-port-permissions")
            return
        # click.echo(ports)
        count = len(ports)
        port = None
        if count == 0:
            pass #scan
        elif count == 1:
            port = ports[0]
        elif count >= 2:
            while 1:
                for x in range(len(ports)):
                    click.echo("%s.) %s" %(x, ports[x]))
                click.secho('? ', fg='green', nl=False)
                value = click.prompt(click.style('Please choice a device', bold=True), type=int)
                if value >= 0 and value < len(ports):
                    port = ports[value]
                    break
                else:
                    click.echo(click.style('>> ', fg='red') + "invalid input.")

        if not port:
            click.secho('> ', fg='green', nl=False)
            click.echo("No devices detected via USB.")
            # click.echo('>> change your network to wio_?')
            click.secho('? ', fg='green', nl=False)
            value = click.confirm(
                click.style('Would you like to enter Wi-Fi setup mode?', bold=True), default=True)

            #### udp setup
            r = upd_send(msvr, msvr_ip, xsvr, xsvr_ip, node_sn, node_key)
            if not r:
                return
            d_name = r['name']
            check_connect(mserver_url, token, node_sn, d_name)
            return
            
        click.echo(click.style('> ', fg='green') + "I have detected a " +
            click.style("Wio ", fg='green') + "connected via USB.")

        r = serial_send(msvr, msvr_ip, xsvr, xsvr_ip, node_sn, node_key, port)
        if not r:
            return
        d_name = r['name']
        check_connect(mserver_url, token, node_sn, d_name)
    elif board == WIO_NODE_V1_0:
        r = upd_send(msvr, msvr_ip, xsvr, xsvr_ip, node_sn, node_key)
        if not r:
            return
        d_name = r['name']
        check_connect(mserver_url, token, node_sn, d_name)
1037336
def start_simple_server():
	""
	args = _get_args()
	addr = ('', args.port)
	DebuggingServer(addr, None)
	asyncore.loop()
461047
def serve(ip, port, application, ssl=None, processes=1, **kwargs):
    

    try:
        # use werkzeug if its there
        from werkzeug.serving import run_simple
        print("Using Werkzeug run_simple")
        run_simple(ip, port, application, ssl_context=ssl, processes=processes, **kwargs)
        return
    except ImportError:
        pass

    # otherwise just use python's built in wsgi webserver
    from wsgiref.simple_server import make_server
    server = make_server(ip, port, application)
    print("Serving on %s:%s, using built in Python server" % (ip, port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
1307741
function Server(server, options)
{
	events.EventEmitter.call(this);
	
	this.listen = function(options, callback) {
		server.listen(options, callback);
	};
	
	server.on('connection', (socket) => {
		options = options || {};
		options.isServer = true;
		this.emit('client', new Client(socket, options));
	});
}
1022174
def _init_publisher_ws(self):
        
        logging.debug("Initializing new web socket connection.")

        url = ('wss://%s/v1/stream/messages/' % self.eventhub_client.host)

        headers = self._generate_publish_headers()

        logging.debug("URL=" + str(url))
        logging.debug("HEADERS=" + str(headers))

        websocket.enableTrace(False)
        self._ws = websocket.WebSocketApp(url,
                                          header=headers,
                                          on_message=self._on_ws_message,
                                          on_open=self._on_ws_open,
                                          on_close=self._on_ws_close)
        self._ws_thread = threading.Thread(target=self._ws.run_forever, kwargs={'ping_interval': 30})
        self._ws_thread.daemon = True
        self._ws_thread.start()
        time.sleep(1)