This method is used to run the websocket app continuously.
            It will execute callbacks as defined and try to stay
            connected with the provided APIs
551723
def run_forever(self):
        
        cnt = 0
        while True:
            cnt += 1
            self.url = next(self.urls)
            log.debug("Trying to connect to node %s" % self.url)
            try:
                # websocket.enableTrace(True)
                self.ws = websocket.WebSocketApp(
                    self.url,
                    on_message=self.on_message,
                    # on_data=self.on_message,
                    on_error=self.on_error,
                    on_close=self.on_close,
                    on_open=self.on_open,
                )
                self.ws.run_forever()
            except websocket.WebSocketException as exc:
                if self.num_retries >= 0 and cnt > self.num_retries:
                    raise NumRetriesReached()

                sleeptime = (cnt - 1) * 2 if cnt < 10 else 10
                if sleeptime:
                    log.warning(
                        "Lost connection to node during wsconnect(): %s (%d/%d) "
                        % (self.url, cnt, self.num_retries)
                        + "Retrying in %d seconds" % sleeptime
                    )
                    time.sleep(sleeptime)

            except KeyboardInterrupt:
                self.ws.keep_running = False
                raise

            except Exception as e:
                log.critical("{}\n\n{}".format(str(e), traceback.format_exc()))
374778
def run_server(self):
        
        self.protocol = MeaseWebSocketServerProtocol

        reactor.listenTCP(port=self.port, factory=self, interface=self.host)

        logger.info("Websocket server listening on {address}".format(
            address=self.address))

        reactor.run()
61012
def run(self, endpoint: str, loop: AbstractEventLoop = None):
        
        if not loop:
            loop = asyncio.get_event_loop()

        try:
            loop.run_until_complete(self.run_async(endpoint))
        except KeyboardInterrupt:
            self._shutdown()
570288
public void run() {
        this.running = true;

        while (this.running) {
            DatagramPacket packet = new DatagramPacket(this.buf, this.buf.length);
            try {
                this.socket.receive(packet);
            } catch (IOException ignored) {
                continue;
            }

            byte[] worker = new byte[2];
            System.arraycopy(this.buf, 2, worker, 0, 2);
            int length = (int)ByteArray.fromBytes(worker);
            worker = new byte[length];
            System.arraycopy(this.buf, 0, worker, 0, length);
            Command msg = new Command(worker, tk);
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            int timeStamp = (int)(System.currentTimeMillis() / 1000L);
            Response resp;
            if (msg.isHello()){
                resp = new Response(this.tk, this.deviceId, timeStamp);
            } else {
                if (msg.getDeviceID() != this.deviceId) continue;
                Object data = executeCommand(msg.getMethod(),msg.getParams());
                if (data == null){
                    data = "unknown_method";
                }
                resp = new Response(this.tk, this.deviceId, timeStamp, msg.getPayloadID(), data);
            }
            byte[] respMsg = resp.create();
            System.arraycopy(respMsg,0,this.buf,0,respMsg.length);
            packet = new DatagramPacket(buf, respMsg.length, address, port);

            try {
                this.socket.send(packet);
            } catch (IOException ignored) {
            }
        }
        this.socket.close();
    }
1211381
def call(method, *args, **kwargs):
    '''
    
    '''
    kwargs = clean_kwargs(**kwargs)
    if not netmiko_device['always_alive']:
        connection = ConnectHandler(**netmiko_device['args'])
        ret = getattr(connection, method)(*args, **kwargs)
        connection.disconnect()
        return ret
    return getattr(netmiko_device['connection'], method)(*args, **kwargs)
640113
def _run(self, *args, **kwargs):
        
        apgw_rpc_bind_ip = _validate_rpc_ip(kwargs.pop(NC_RPC_BIND_IP))
        apgw_rpc_bind_port = _validate_rpc_port(kwargs.pop(NC_RPC_BIND_PORT))

        sock_addr = (apgw_rpc_bind_ip, apgw_rpc_bind_port)
        LOG.debug('NetworkController started listening for connections...')

        server_thread, _ = self._listen_tcp(sock_addr,
                                            self._start_rpc_session)
        self.pause(0)
        server_thread.wait()
420021
function WebsocketConnection(socket, url) {
  this.socket = socket;
  this.url = url;

  this.deferreds = {};
  this.nextRequestId = 0;

  this.onReply = this.onReply.bind(this);
  this.onEvent = this.onEvent.bind(this);
}
1191420
def run_forever(self):
        """"""
        res = self.slack.rtm.start()
        self.log.info("current channels: %s",
                      ','.join(c['name'] for c in res.body['channels']
                               if c['is_member']))
        self.id = res.body['self']['id']
        self.name = res.body['self']['name']
        self.my_mention = "<@%s>" % self.id

        self.ws = websocket.WebSocketApp(
            res.body['url'],
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close,
            on_open=self._on_open)
        self.prepare_connection(self.config)
        self.ws.run_forever()
787928
@Override
	public void run() {
		while (running) {
			try {
				// Read the request
				service.execute(new HttpSession(this, socket.accept()));
			} catch (IOException e) {
				// Ignore mostly.
			}
		}
	}
1229487
def run_tornado(self, args):
        
        server = self
        import tornado.ioloop
        import tornado.web
        import tornado.websocket

        ioloop = tornado.ioloop.IOLoop.current()

        class DevWebSocketHandler(tornado.websocket.WebSocketHandler):
            def open(self):
                super(DevWebSocketHandler, self).open()
                server.on_open(self)

            def on_message(self, message):
                server.on_message(self, message)

            def on_close(self):
                super(DevWebSocketHandler, self).on_close()
                server.on_close(self)

        class MainHandler(tornado.web.RequestHandler):
            def get(self):
                self.write(server.index_page)

        #: Set the call later method
        server.call_later = ioloop.call_later
        server.add_callback = ioloop.add_callback

        app = tornado.web.Application([
            (r"/", MainHandler),
            (r"/dev", DevWebSocketHandler),
        ])

        app.listen(self.port)
        print("Tornado Dev server started on {}".format(self.port))
        ioloop.start()
607584
def run_once(self):
        
        # pylint: disable=too-many-branches, too-many-return-statements

        try:
            if not self._check_connection():
                return 0
        except ChromecastConnectionError:
            return 1

        # poll the socket
        can_read, _, _ = select.select([self.socket], [], [], self.polltime)

        # read messages from chromecast
        message = data = None
        if self.socket in can_read and not self._force_recon:
            try:
                message = self._read_message()
            except InterruptLoop as exc:
                if self.stop.is_set():
                    self.logger.info(
                        "[%s:%s] Stopped while reading message, "
                        "disconnecting.",
                        self.fn or self.host, self.port)
                else:
                    self.logger.error(
                        "[%s:%s] Interruption caught without being stopped: "
                        "%s",
                        self.fn or self.host, self.port, exc)
                return 1
            except ssl.SSLError as exc:
                if exc.errno == ssl.SSL_ERROR_EOF:
                    if self.stop.is_set():
                        return 1
                raise
            except socket.error:
                self._force_recon = True
                self.logger.error('[%s:%s] Error reading from socket.',
                                  self.fn or self.host, self.port)
            else:
                data = _json_from_message(message)
        if not message:
            return 0

        # If we are stopped after receiving a message we skip the message
        # and tear down the connection
        if self.stop.is_set():
            return 1

        # See if any handlers will accept this message
        self._route_message(message, data)

        if REQUEST_ID in data:
            callback = self._request_callbacks.pop(data[REQUEST_ID], None)
            if callback is not None:
                event = callback['event']
                callback['response'] = data
                function = callback['function']
                event.set()
                if function:
                    function(data)

        return 0
1047873
def run(self):
        
        self.pre_run()
        first = True
        while self.runnable:
            self.pre_call_message()

            if first:
                self.pre_first_call_message()
            
            message, payload = self.listener.get()
            getattr(self, message)(payload)

            if first:
                first = False
                self.post_first_call_message()
                
            self.post_call_message()

        self.post_run()
498964
def run(self):
        ''''''
        while not self.wait(self.delay()):
            try:
                logger.info('Invoking callback %s', self.callback)
                self.callback()
            except StandardError:
                logger.exception('Callback failed')
1293657
def run!(runtime_config = {})
			@websocket_config.merge! runtime_config

			EM.run do
				if @websocket_config[:tick_interval]
					EM.add_periodic_timer(@websocket_config[:tick_interval]) do
						socket_trigger(:on_tick, @socket_connected)
					end
				end

				EventMachine::WebSocket.run(host: @websocket_config[:socket_host], port: @websocket_config[:socket_port]) do |socket|
					@socket_active = socket
					socket.onopen do |handshake|
						@socket_connected = true
						socket_trigger(:on_socket_open, handshake)
					end

					socket.onmessage do |msg| 
						process_message(msg)
					end

					socket.onclose do 
						socket_trigger(:on_socket_close)
						@socket_connected = false 
					end
				end
			 
				Launchy.open("http://#{@websocket_config[:http_host]}:#{@websocket_config[:http_port]}/")
				WebsocketGui::SinatraWrapper.view_path = @websocket_config[:view]
				WebsocketGui::SinatraWrapper.run!(
					port: @websocket_config[:http_port], 
					bind: @websocket_config[:http_host])
			end
		end
1282564
def execute(self):
        
        stack = self._stack
        callbacks = self._callbacks
        self._stack = []
        self._callbacks = []

        deferred = []

        build = self._nested_future

        pipe = self._pipeline(self.connection_name)
        for item, args, kwargs, ref in stack:
            f = getattr(pipe, item)
            deferred.append(build(f(*args, **kwargs), ref))

        inject_callbacks = getattr(self.parent, '_inject_callbacks')
        inject_callbacks(deferred + callbacks)
963314
def run(self):
        

        server_logger = logging.getLogger('aiohttp.server')
        # In debug mode we don't use the standard request log but a more complete in response.py
        if log.getEffectiveLevel() == logging.DEBUG:
            server_logger.setLevel(logging.CRITICAL)

        logger = logging.getLogger("asyncio")
        logger.setLevel(logging.ERROR)

        if sys.platform.startswith("win"):
            loop = asyncio.get_event_loop()
            # Add a periodic callback to give a chance to process signals on Windows
            # because asyncio.add_signal_handler() is not supported yet on that platform
            # otherwise the loop runs outside of signal module's ability to trap signals.

            def wakeup():
                loop.call_later(0.5, wakeup)
            loop.call_later(0.5, wakeup)

        server_config = Config.instance().get_section_config("Server")

        ssl_context = None
        if server_config.getboolean("ssl"):
            if sys.platform.startswith("win"):
                log.critical("SSL mode is not supported on Windows")
                raise SystemExit
            ssl_context = self._create_ssl_context(server_config)

        self._loop = asyncio.get_event_loop()

        if log.getEffectiveLevel() == logging.DEBUG:
            # On debug version we enable info that
            # coroutine is not called in a way await/yield from
            self._loop.set_debug(True)

        for key, val in os.environ.items():
            log.debug("ENV %s=%s", key, val)

        self._app = aiohttp.web.Application()
        # Background task started with the server
        self._app.on_startup.append(self._on_startup)

        # Allow CORS for this domains
        cors = aiohttp_cors.setup(self._app, defaults={
            # Default web server for web gui dev
            "http://127.0.0.1:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://localhost:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://127.0.0.1:4200": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://localhost:4200": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "https://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*")
        })

        PortManager.instance().console_host = self._host

        for method, route, handler in Route.get_routes():
            log.debug("Adding route: {} {}".format(method, route))
            cors.add(self._app.router.add_route(method, route, handler))
        for module in MODULES:
            log.debug("Loading module {}".format(module.__name__))
            m = module.instance()
            m.port_manager = PortManager.instance()

        log.info("Starting server on {}:{}".format(self._host, self._port))

        self._handler = self._app.make_handler()
        if self._run_application(self._handler, ssl_context) is False:
            self._loop.stop()
            return

        self._signal_handling()
        self._exit_handling()

        if server_config.getboolean("shell"):
            asyncio.async(self.start_shell())

        try:
            self._loop.run_forever()
        except TypeError as e:
            # This is to ignore an asyncio.windows_events exception
            # on Windows when the process gets the SIGBREAK signal
            # TypeError: async() takes 1 positional argument but 3 were given
            log.warning("TypeError exception in the loop {}".format(e))
        finally:
            if self._loop.is_running():
                self._loop.run_until_complete(self.shutdown_server())
926609
def run(self):
        
        while True:
            self._logger.debug('Accepting connection')
            conn, addr = self._sock.accept()
            self._talk = SocketTalk(conn, encode=self._encode)

            self._logger.debug('Receiving action')
            action = self._receive()

            if self._on_action:
                self._on_action(action)

            key = None
            if action in ('set', 'get', 'del',):
                self._logger.debug('Receiving key')
                key = self._receive()

            value = None
            if action in ('set',):
                self._logger.debug('Receiving value')
                value = self._receive()

            # Process the request.
            if action == 'stop':
                self._send('ok')

            elif action == 'set':
                self._data[key] = value
                self._send('ok')

            elif action == 'get':
                try:
                    value = self._data[key]
                except:
                    self._logger.debug('Sending "key not found"')
                    self._send('key not found')
                else:
                    self._logger.debug('Sending "ok"')
                    self._send('ok')
                    self._logger.debug('Sending value')
                    self._send(value)

            elif action == 'del':
                try:
                    del self._data[key]
                except:
                    self._logger.debug('Sending "key not found"')
                    self._send('key not found')
                else:
                    self._logger.debug('Sending "ok"')
                    self._send('ok')

            elif action == 'size':
                self._send('ok')
                self._send(str(len(self._data)))

            elif action == 'keys':
                pickled = pickle.dumps(self._data.keys())
                self._send('ok')
                self._send(pickled)

            else:
                self._send('unknown action %s' % action)

            self._logger.debug('Closing')
            try:
                conn.shutdown(socket.SHUT_RDWR)
            except:
                self._logger.error('Failed to shutdown')
            conn.close()

            if action == 'stop':
                break

        self._logger.debug('Stopped')