Waits and receives messages from the server. This
            function somewhat needs to block so is executed in its
            own thread until self._request_shutdown is called.
480592
def run(self):
        
        while not self._request_shutdown:

            # Find out if we have any data pending from the
            # server
            try:

                # If we've been asked to stop running the
                # request loop. We'll just sit and wait
                # till we get asked to run again
                if self._state not in [STATE_AUTHENTICATING,STATE_WEBSOCKET_CONNECTED,STATE_CONNECTED]:
                    self._request_loop_notify_restart.acquire()
                    self._request_loop_notify_restart.wait(self._loop_timeout)
                    self._request_loop_notify_restart.release()
                    continue

                # If we don't have a websocket defined.
                # we don't go further either
                elif not self.ws:
                    logger.debug("No longer have a websocket. Marking disconnected")
                    self._state = STATE_DISCONNECTED
                    continue

                # Okay, we think we're okay so let's try and read some data
                data = self.ws.recv()
            except io.BlockingIOError:
                continue
            except websocket.WebSocketTimeoutException:
                continue
            except websocket.WebSocketConnectionClosedException as ex:
                logger.debug("WebSocketConnectionClosedException: Requesting disconnect:".format(ex))
                self.disconnect()

                # If the server disconnected, let's try and reconnect
                # back to the service after a random few seconds
                if self.auto_reconnect:
                    # As doing a reconnect would block and would then
                    # prevent us from ticking the websoocket, we'll
                    # go into a subthread to deal with the reconnection
                    def reconnect():
                        self.reconnect()
                    t = threading.Thread(target=reconnect)
                    t.start()

                    # FIXME: need to randomly wait
                    time.sleep(1)
                    if not data: continue
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
                continue

            try:
                logger.debug("<RCV: {}".format(data))
                message = WampMessage.loads(data)
                logger.debug("<RCV: {}".format(message.dump()))
                try:
                    code_name = message.code_name.lower()
                    handler_name = "handle_"+code_name
                    handler_function = getattr(self,handler_name)
                    handler_function(message)
                except AttributeError as ex:
                    self.handle_unknown(message)
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
591856
private void receive() {
    try {
      Socket socket = null;
      BufferedReader reader = null;
      try {
        // connect to the server
        socket = new Socket(host, port);
        reader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        // Until stopped or connection broken continue reading
        String userInput;
        while (!isStopped() && (userInput = reader.readLine()) != null) {
          System.out.println("Received data '" + userInput + "'");
          store(userInput);
        }
      } finally {
        Closeables.close(reader, /* swallowIOException = */ true);
        Closeables.close(socket,  /* swallowIOException = */ true);
      }
      // Restart in an attempt to connect again when server is active again
      restart("Trying to connect again");
    } catch(ConnectException ce) {
      // restart if could not connect to server
      restart("Could not connect", ce);
    } catch(Throwable t) {
      restart("Error receiving data", t);
    }
  }
249888
def receive(self):
        """"""
        while True:
            try:
                # read data from the buffer
                data = self.socket.recv(self._socket_recv)
            except socket.timeout as e:
                _LOGGER.debug(e)
                sleep(1)
                return
            except socket.error as e:
                # Something else happened
                _LOGGER.error(e)
                return

            else:
                if len(data) == 0:
                    # no more data being transmitted
                    _LOGGER.info('orderly shutdown on server end')
                    return

                # remove trailing carriage return, then split
                # on carriage return (for multi-line replies)
                results = data.decode('ascii').rstrip('\r').split('\r')
                if len(results) > 1:
                    _LOGGER.debug("multi-line reply")
                for result in results:
                    _LOGGER.debug("receive thread: " + result)
                    self.queue.put(result)
14213
def wait(self):
        
        self.wait_event = threading.Event()
        timeout = int(self.timeout) if self.timeout else None
        self.timed_out = not self.wait_event.wait(timeout)
534191
public void shutdownAndWait() {
		try {
			client.shutdown().get();
			LOG.info("The Queryable State Client was shutdown successfully.");
		} catch (Exception e) {
			LOG.warn("The Queryable State Client shutdown failed: ", e);
		}
	}
1092768
def request_blocking(self, method, params):
        
        response = self._make_request(method, params)

        if "error" in response:
            raise ValueError(response["error"])

        return response['result']
473125
def request_halt(self, req, msg):
        
        f = Future()
        @gen.coroutine
        def _halt():
            req.reply("ok")
            yield gen.moment
            self.stop(timeout=None)
            raise AsyncReply

        self.ioloop.add_callback(lambda: chain_future(_halt(), f))
        return f
1206748
async def _client_run_async(self):
        
        # pylint: disable=protected-access
        self._waiting_messages = 0
        async with self._pending_messages_lock:
            self._pending_messages = await self._filter_pending_async()
        if self._backoff and not self._waiting_messages:
            _logger.info("Client told to backoff - sleeping for %r seconds", self._backoff)
            await self._connection.sleep_async(self._backoff)
            self._backoff = 0
        await asyncio.shield(self._connection.work_async())
        return True
365676
def listen(self, timeout=10):
        
        self._socket.settimeout(float(timeout))
        while not self.stopped.isSet():
            try:
                data, client_address = self._socket.recvfrom(4096)
            except socket.timeout:
                continue
            try:
                #Start a new thread not to block other requests
                args = ((data, client_address), )
                t = threading.Thread(target=self.receive_datagram, args=args)
                t.daemon = True
                t.start()
            except RuntimeError:
                logging.exception("Exception with Executor")
        logging.debug("closing socket")
        self._socket.close()
664054
def _recv_thread(self):
        
        for msg, metadata in self._source:
            if msg.msg_type:
                self._call(msg, **metadata)
        # Break any upstream iterators
        for sink in self._sinks:
            i = sink()
            if i is not None:
                i.breakiter()
        self._dead = True
387612
protected void sendRequests() {
        if ( ! requestUnderway ) {
            requestUnderway = true;
            delayed( new Runnable() {
                @Override
                public void run() {
                    synchronized (requests) {
                        Object req[];
                        if ( openFutureRequests.get() > 0 && requests.size() == 0 ) {
                            req = new Object[] { "SP", lastSeenSeq };
                        } else {
                            req = new Object[requests.size() + 1];
                            for (int i = 0; i < requests.size(); i++) {
                                req[i] = requests.get(i);
                            }
                            req[req.length - 1] = lastSeenSeq;
                            requests.clear();
                        }

                        sendCallArray(req).then(new Callback<Integer>() {
                            @Override
                            public void receive(Integer result, Object error) {
                                synchronized (requests ) {
                                    requestUnderway = false;
                                    if ( requests.size() > 0 || (result != null && result > 0 && openFutureRequests.get() > 0 ) ) {
                                        myExec.execute(new Runnable() {
                                            @Override
                                            public void run() {
                                            sendRequests();
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            }, 1);
        }
    }
279795
def wait(self):
        
        if self.error:
            raise self.error
        if not self.running:
            raise ValueError("Unable to send until client has been started.")
        try:
            self._handler.wait()
        except (errors.TokenExpired, errors.AuthenticationException):
            log.info("Sender disconnected due to token error. Attempting reconnect.")
            self.reconnect()
        except (errors.LinkDetach, errors.ConnectionClose) as shutdown:
            if shutdown.action.retry and self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except errors.MessageHandlerError as shutdown:
            if self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except Exception as e:
            log.info("Unexpected error occurred (%r).", e)
            raise EventHubError("Send failed: {}".format(e))
115252
def receive(timeout = nil, &block)
      loop do
        message = @receivers.receive(timeout, &block)
        return message unless message.is_a?(SystemEvent)

        handle_system_event(message)
      end
    end
318454
def send_request(self, request):
        
        assert self._handshake_performed, "Perform a handshake first."

        assert request.id not in self._outbound_pending_call, (
            "Message ID '%d' already being used" % request.id
        )

        future = tornado.gen.Future()
        self._outbound_pending_call[request.id] = future
        self.add_pending_outbound()
        self.stream_request(request, future).add_done_callback(
            lambda f: self.remove_pending_outbound()
        )

        if request.ttl:
            self._add_timeout(request, future)

        # the actual future that caller will yield
        response_future = tornado.gen.Future()
        # TODO: fire before_receive_response

        IOLoop.current().add_future(
            future,
            lambda f: self.adapt_result(f, request, response_future),
        )
        return response_future
191352
def receive(self):
        '''
        
        '''
        while self.buffer.empty() and self.__up:
            # This sequence is skipped when the buffer is not empty.
            sleep_ms = random.randint(0, 1000)
            # log.debug('The message queue is empty, waiting %d miliseconds', sleep_ms)
            # disabled ^ as it was too noisy
            time.sleep(sleep_ms / 1000.0)
        if not self.buffer.empty():
            return self.buffer.get(block=False)
        return '', ''
1140189
def send_request(self, request, callback=None, timeout=None, no_response=False):  # pragma: no cover
        
        if callback is not None:
            thread = threading.Thread(target=self._thread_body, args=(request, callback))
            thread.start()
        else:
            self.protocol.send_message(request)
            if no_response:
                return
            try:
                response = self.queue.get(block=True, timeout=timeout)
            except Empty:
                #if timeout is set
                response = None
            return response
64693
def send_message(
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:
        
        payload = str(request) + self.delimiter
        self.socket.send(payload.encode(self.encoding))

        response = bytes()
        decoded = None

        # Receive the response until we find the delimiter.
        # TODO Do not wait for a response if the message sent is a notification.
        while True:
            response += self.socket.recv(1024)

            decoded = response.decode(self.encoding)
            if len(decoded) < self.delimiter_length:
                continue

            # TODO Check that're not in the middle of the response.
            elif decoded[-self.delimiter_length :] == self.delimiter:
                break

        assert decoded is not None
        return Response(decoded[: -self.delimiter_length])