Add command to initialize the websocket server
487155
public function addProcess(ProcessSpawnerEvent $event) {
    
    if ((bool)Config::getOption("plugins.reload.enabled")) {
      
      // only run this command if watch is going to be used
      if (Console::findCommand("w|watch") || Console::findCommandOption("with-watch")) {
        
        // set-up the command
        $pathPHP      = Console::getPathPHP();
        $pathReload   = __DIR__."/AutoReloadServer.php";
        $command      = "exec ".$pathPHP." ".$pathReload;
        
        // send the processes on their way
        $processes     = array();
        $processes[]   = array("command" => $command, "timeout" => null, "idle" => 600, "output" => false);
        $event->addPluginProcesses($processes);
        
      }
      
    }
    
  }
303176
function init() {
  // In development, we need to open a socket to listen for changes to data
  if (process.env.REACT_STATIC_ENV === 'development') {
    const io = require('socket.io-client')
    const run = async () => {
      try {
        const {
          data: { port },
        } = await axios.get('/__react-static__/getMessagePort')
        const socket = io(`http://localhost:${port}`)
        socket.on('connect', () => {
          // Do nothing
        })
        socket.on('message', ({ type }) => {
          if (type === 'reloadClientData') {
            reloadClientData()
          }
        })
      } catch (err) {
        console.log(
          'React-Static data hot-loader websocket encountered the following error:'
        )
        console.error(err)
      }
    }
    run()
  }

  if (process.env.REACT_STATIC_DISABLE_PRELOAD === 'false') {
    startPreloader()
  }
}
206792
def start_server():
    """"""
    parser = argparse.ArgumentParser(description="Opens a browser-based "
                                     "client that interfaces with the "
                                     "chemical format converter.")
    parser.add_argument('--debug', action="store_true", help="Prints all "
                        "transmitted data streams.")
    parser.add_argument('--port', type=int, default=8000, help="The port "
                        "on which to serve the website.")
    parser.add_argument('--timeout', type=int, default=5, help="The maximum "
                        "time, in seconds, allowed for a process to run "
                        "before returning an error.")
    parser.add_argument('--workers', type=int, default=2, help="The number of "
                        "worker processes to use with the server.")
    parser.add_argument('--no-browser', action="store_true", help="Disables "
                        "opening a browser window on startup.")
    global args
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
                (r'/static/(.*)', tornado.web.StaticFileHandler,
                 {'path': os.path.normpath(os.path.dirname(__file__))})]
    application = tornado.web.Application(handlers)
    application.listen(args.port)

    if not args.no_browser:
        webbrowser.open('http://localhost:%d/' % args.port, new=2)

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
        tornado.ioloop.IOLoop.instance().stop()
        sys.exit(1)
125873
function run() {
		$fw=\Base::instance();
		// Assign signal handlers
		declare(ticks=1);
		pcntl_signal(SIGINT,[$this,'kill']);
		pcntl_signal(SIGTERM,[$this,'kill']);
		gc_enable();
		// Activate WebSocket listener
		$listen=stream_socket_server(
			$this->addr,$errno,$errstr,
			STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
			$this->ctx
		);
		$socket=socket_import_stream($listen);
		register_shutdown_function(function() use($listen) {
			foreach ($this->sockets as $socket)
				if ($socket!=$listen)
					$this->close($socket);
			$this->close($listen);
			if (isset($this->events['stop']) &&
				is_callable($func=$this->events['stop']))
				$func($this);
		});
		if ($errstr)
			user_error($errstr,E_USER_ERROR);
		if (isset($this->events['start']) &&
			is_callable($func=$this->events['start']))
			$func($this);
		$this->sockets=[(int)$listen=>$listen];
		$empty=[];
		$wait=$this->wait;
		while (TRUE) {
			$active=$this->sockets;
			$mark=microtime(TRUE);
			$count=@stream_select(
				$active,$empty,$empty,(int)$wait,round(1e6*($wait-(int)$wait))
			);
			if (is_bool($count) && $wait) {
				if (isset($this->events['error']) &&
					is_callable($func=$this->events['error']))
					$func($this);
				die;
			}
			if ($count) {
				// Process active connections
				foreach ($active as $socket) {
					if (!is_resource($socket))
						continue;
					if ($socket==$listen) {
						if ($socket=@stream_socket_accept($listen,0))
							$this->alloc($socket);
						else
						if (isset($this->events['error']) &&
							is_callable($func=$this->events['error']))
							$func($this);
					}
					else {
						$id=(int)$socket;
						if (isset($this->agents[$id]))
							$this->agents[$id]->fetch();
					}
				}
				$wait-=microtime(TRUE)-$mark;
				while ($wait<1e-6) {
					$wait+=$this->wait;
					$count=0;
				}
			}
			if (!$count) {
				$mark=microtime(TRUE);
				foreach ($this->sockets as $id=>$socket) {
					if (!is_resource($socket))
						continue;
					if ($socket!=$listen &&
						isset($this->agents[$id]) &&
						isset($this->events['idle']) &&
						is_callable($func=$this->events['idle']))
						$func($this->agents[$id]);
				}
				$wait=$this->wait-microtime(TRUE)+$mark;
			}
			gc_collect_cycles();
		}
	}
1074443
def run_websocket_server(self, host='localhost', port=9090, debug=False):
        
        from .server import MeaseWebSocketServerFactory

        websocket_factory = MeaseWebSocketServerFactory(
            mease=self, host=host, port=port, debug=debug)
        websocket_factory.run_server()
1274401
def on_open(self, websocket):
        ''''''
        self.pubsub.add_client(ChatClient(websocket, self.channel))
163973
public synchronized void init(int serverPort)
    {
        if (this.initialized)
        {
            return;
        }

        String hostname = null;

        try
        {
            hostname = InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException ex)
        {
            logger.warn("Get host failed. Use localhost.", ex);
        }

        logger.info("WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}",
                hostname, serverPort, "/", this.toString());
        this.server = new Server(hostname, serverPort, "/", null, AmLogServerEndPoint.class);
        try
        {
            this.server.start();
        }
        catch (DeploymentException ex)
        {
            logger.warn("WebSocket server initialize failed. Skip initialize.", ex);
        }

        this.initialized = true;
    }
819087
function server(options) {
  status = 'server.started'
  config = _.extend(defaultServerOptions, options)

  open(config.datafile)

  if (config.logToConsole)
    console.log("✔ log to stdout")

  // ws [
  var ServerMessageLog = {}
  var queueMessages = []
  var timer

  function flushMessages(n) {
    queueMessages = _.sortBy(queueMessages, 'time')
    var messages = queueMessages.slice(0, n)
    queueMessages = queueMessages.slice(n)
//    console.log(messages);
    _.each(messages, function (m) {
//      var filename = options.logpath+'/1.log'
//      logString(filename, m.text)
      logMessage(new Date(m.time), m.path, m.data, m.type == 'log' ? '' : m.type)
    })
  }

  console.log("✔ ws server listening on port %d", config.port)

  var wss = new WebSocketServer({port: config.port});

  wss.on('connection', function(ws) {
    ws.on('message', function(m) {
      var message = JSON.parse(m)
      queueMessages.push(message)
      if (queueMessages.length > config.queueMessagesMax)
        flushMessages(config.flushMessagesCount)

      if (timer)
        clearTimeout(timer)
      timer = setTimeout(function () {
        timer = null
        flushMessages(queueMessages.length)
      }, config.serverFlushTimeout)
    })
  })
  // ws ]
}
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
41826
function ws(argv, callback) {
  if (!argv[2]) {
    console.error("url is required");
    console.error("Usage : ws <url>");
    process.exit(-1);
  }
  var uri = argv[2];
  var updatesVia = 'wss://' + uri.split('/')[2] + '/';

  var s;

  var connect = function(){
    s = new wss(updatesVia, {
      origin: 'http://websocket.org'
    });

    s.on('error', function() {
      callback('socket error');
      setTimeout(connect, RECONNECT);
    });

    s.on('open', function open() {
      var sub = 'sub ' + uri;
      callback(null, sub);
      s.send(sub);

      // periodically ping server
      setInterval(function() {
        var message = 'ping';
        debug(null, message);
        s.send(message);
      }, INTERVAL);
    });

  };
  connect();

  s.on('message', function message(data, flags) {
    callback(null, data);
  });

}
378213
function init(shard, socket) {  // {{{2
/**
 * Sends request to the master shard to establish a link.
 *
 * @param shard {Object} Slave shard
 * @param ws {Object} WebSocket
 *
 * @method constructor
 */

  if (shard.slaves) {
    if (socket._lid in shard.slaves) {
      return L.error(socket, O.log.todo('Duplicit lid', shard, socket._lid));
    }
  } else {
    shard.slaves = {};
  }

  this.shard = shard;
  shard.slaves[socket._lid] = this;

  return L.open(this, socket, {
    home: shard.isAtHome() || shard.masterState === shard.MASTER_STATE.HOME,
    homeTime: Date.now() + shard.homeTimeOffset,
  });
}
17911
function init(space, socket) {  // {{{2
/**
 * Sends request to the master space to establish a link.
 *
 * @param space {Object} Slave space
 * @param ws {Object} WebSocket
 *
 * @method constructor
 */

  if (space.slaves) {
    if (socket._lid in space.slaves) {
      O.link.error(socket, O.log.todo('Duplicit lid', space, socket._lid));
      return;
    }
  } else {
    space.slaves = {};
  }

  this.space = space;
  space.slaves[socket._lid] = this;

  O.link.open(this, socket, {home: space.isAtHome() || space.masterState === space.MASTER_STATE.HOME})
  return;
}
246767
function init(msg, done) {
  var config = {
    context: opts.context,
    adapter: opts.adapter,
    routes: opts.routes,
    auth: opts.auth,
    options: opts.options
  }

  setServer.call(this, config, done)
}
1102110
function ws_oneditprepare() {
            $("#websocket-client-row").hide();
            $("#node-input-mode").change(function() {
                if ( $("#node-input-mode").val() === 'client') {
                    $("#websocket-server-row").hide();
                    $("#websocket-client-row").show();
                }
                else {
                    $("#websocket-server-row").show();
                    $("#websocket-client-row").hide();
                }
            });
    
            if (this.client) {
                $("#node-input-mode").val('client').change();
            }
            else {
                $("#node-input-mode").val('server').change();
            }
        }
1146679
protected function init()
    {
        $this->addCommand(Queue\WorkerCommand::class);
        $this->addCommand(Queue\TableCommand::class);
        $this->addCommand(Queue\FailedTableCommand::class);
        $this->addCommand(Queue\RetryCommand::class);
        $this->addCommand(Queue\RestartCommand::class);
        $this->addCommand(Queue\RemoveFailedCommand::class);
    }
1190944
function startBrowserSync(serverRoot) {

    helper.log('Starting BrowserSync on port ' + 8080 + ' for ' + serverRoot);

    var options = {
        //proxy: 'localhost:' + port,
        port: 8080,
        ws: true,
        server: {
            baseDir: serverRoot
        },
        reloadDelay: config.browserReloadDelay
    };

    browserSync.init(options);

}
537410
protected function init()
    {
        $this->addCommand(new SyncCommand());
        $this->addCommand(new MakesumCommand());

        $this->addGlobalOption('e')
            ->alias('env')
            ->description('The environment application name or class.')
            ->defaultValue('dev');
    }