Return the next text or binary message from the socket.

        This is an internal method as calling this will not cleanup correctly
        if an exception is called. Use `receive` instead.
15628
def read_message(self):
        
        opcode = None
        message = None
        while True:
            header, payload = self.read_frame()
            f_opcode = header.opcode
            if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY):
                # a new frame
                if opcode:
                    raise WebSocketError("The opcode in non-fin frame is expected to be zero, got {0!r}".format(f_opcode))
                # Start reading a new message, reset the validator
                self.utf8validator.reset()
                self.utf8validate_last = (True, True, 0, 0)
                opcode = f_opcode
            elif f_opcode == self.OPCODE_CONTINUATION:
                if not opcode:
                    raise WebSocketError("Unexpected frame with opcode=0")
            elif f_opcode == self.OPCODE_PING:
                self.handle_ping(header, payload)
                continue
            elif f_opcode == self.OPCODE_PONG:
                self.handle_pong(header, payload)
                continue
            elif f_opcode == self.OPCODE_CLOSE:
                self.handle_close(header, payload)
                return
            else:
                raise WebSocketError("Unexpected opcode={0!r}".format(f_opcode))
            if opcode == self.OPCODE_TEXT:
                self.validate_utf8(payload)
                if six.PY3:
                    payload = payload.decode()
            if message is None:
                message = six.text_type() if opcode == self.OPCODE_TEXT else six.binary_type()
            message += payload
            if header.fin:
                break
        if opcode == self.OPCODE_TEXT:
            if six.PY2:
                self.validate_utf8(message)
            else:
                self.validate_utf8(message.encode())
            return message
        else:
            return bytearray(message)
829639
def receive():
    
    header = _in_file.read(8)
    logging.getLogger(__name__).debug('Received command, header: [%s]' % header)
    if header is None or len(header) < 8:
        # Pipe EOF encountered
        logging.getLogger(__name__).debug('Pipe EOF encountered')
        return None, None
    length = int(header[2:])
    data = _in_file.read(length)
    command = CommandType(header[:2])
    data = data.decode('utf8')
    logging.getLogger(__name__).debug('Received command, data: [%s]' % data)
    return command, data
170529
def next(self):
        
        # We pick the first outgoing available and send it.
        outgoing_msg = self.outgoing_msg_list.pop_first()
        # If we do not have any outgoing msg., we wait.
        if outgoing_msg is None:
            self.outgoing_msg_event.clear()
            self.outgoing_msg_event.wait()
            outgoing_msg = self.outgoing_msg_list.pop_first()

        return outgoing_msg
157868
def recv(self):
        """"""
        LOGGER.debug('Receiving')
        try:
            message_length = struct.unpack('>i', self._socket.recv(4))[0]
            message_length -= Connection.COMM_LENGTH
            LOGGER.debug('Length: %i', message_length)
        except socket.timeout:
            return None
        
        comm_status = struct.unpack('>i', self._socket.recv(4))[0]
        LOGGER.debug('Status: %i', comm_status)
        bytes_received = 0
        message = b""
        
        while bytes_received < message_length:
            if message_length - bytes_received >= 1024:
                recv_len = 1024
            else:
                recv_len = message_length - bytes_received
            bytes_received += recv_len
            LOGGER.debug('Received %i', bytes_received)
            message += self._socket.recv(recv_len)
        
        if comm_status == 0:
            message = self._crypt.decrypt(message)
        else:
            return Message(len(message), Connection.COMM_ERROR, message)
        
        msg = Message(message_length, comm_status, message)

        return msg
21134
def receive(self, ikpdb):
        
        # with self._connection_lock:
        while self._network_loop:
            _logger.n_debug("Enter socket.recv(%s) with self._received_data = %s", 
                            self.SOCKET_BUFFER_SIZE, 
                            self._received_data)
            try:
                # We may land here with a full packet already in self.received_data
                # In that case we must not enter recv() 
                if self.SOCKET_BUFFER_SIZE:
                    data = self._connection.recv(self.SOCKET_BUFFER_SIZE)
                else:
                    data = b''
                _logger.n_debug("Socket.recv(%s) => %s", self.SOCKET_BUFFER_SIZE, data)

            except socket.timeout:
                _logger.n_debug("socket.timeout witk ikpdb.status=%s", ikpdb.status)
                if ikpdb.status == 'terminated':
                    _logger.n_debug("breaking IKPdbConnectionHandler.receive() "
                                    "network loop as ikpdb state is 'terminated'.")
                    return {    
                        'command': '_InternalQuit',
                        'args':{}
                    }
                continue

            except socket.error as socket_err:
                if ikpdb.status == 'terminated':
                    return {'command': '_InternalQuit', 
                            'args':{'socket_error_number': socket_err.errno,
                                    'socket_error_str': socket_err.strerror}}
                continue
            
            except Exception as exc:
                _logger.g_error("Unexecpected Error: '%s' in IKPdbConnectionHandler"
                                ".command_loop.", exc)
                _logger.g_error(traceback.format_exc())
                print("".join(traceback.format_stack()))
                return {    
                    'command': '_InternalQuit',
                    'args':{
                        "error": exc.__class__.__name__,
                        "message": exc.message
                    }
                }
    
            # received data is utf8 encoded
            self._received_data += data.decode('utf-8')
                
            # have we received a MAGIC_CODE
            try:
                magic_code_idx = self._received_data.index(self.MAGIC_CODE)
            except ValueError:
                continue
            
            # Have we received a 'length='
            try:
                length_idx = self._received_data.index(u'length=')
            except ValueError:
                continue
            
            # extract length content from received data
            json_length = int(self._received_data[length_idx + 7:magic_code_idx])
            message_length = magic_code_idx + len(self.MAGIC_CODE) + json_length
            if message_length <= len(self._received_data):
                full_message = self._received_data[:message_length]
                self._received_data = self._received_data[message_length:]
                if len(self._received_data) > 0:
                    self.SOCKET_BUFFER_SIZE = 0
                else:
                    self.SOCKET_BUFFER_SIZE = 4096
                break
            else:
                self.SOCKET_BUFFER_SIZE = message_length - len(self._received_data)

        self.log_received(full_message)
        obj = self.decode(full_message)
        return obj
945630
def receive(self, decode=True):
        
        payload = self.socket.recv()
        payload = self.verify(payload)
        if decode:
            payload = self.decode(payload)
        return payload
450099
def receive_message(self, header, message):
        """"""

        print("=== Receive ===")
        print(header)
        print(message)

        print("MsgID: {0}".format(header["message-id"]))
        assert header["message-id"]

        txn = self._transport.transaction_begin()
        print(" 1. Txn: {0}".format(str(txn)))
        if self.crashpoint():
            self._transport.transaction_abort(txn)
            print("---  Abort  ---")
            return

        self._transport.ack(header["message-id"], self.subid, transaction=txn)
        print(" 2. Ack")
        if self.crashpoint():
            self._transport.transaction_abort(txn)
            print("---  Abort  ---")
            return

        self._transport.send("transient.destination", message, transaction=txn)
        print(" 3. Send")

        if self.crashpoint():
            self._transport.transaction_abort(txn)
            print("---  Abort  ---")
            return

        self._transport.transaction_commit(txn)
        print(" 4. Commit")
        print("===  Done   ===")
440361
def on_receive(self, broker):
        
        buf = self.receive_side.read()
        if not buf:
            return self.on_disconnect(broker)

        self.buf += buf.decode('utf-8', 'replace')
        while u'\n' in self.buf:
            lines = self.buf.split('\n')
            self.buf = lines[-1]
            for line in lines[:-1]:
                LOG.debug('%s: %s', self.stream.name, line.rstrip())
638798
def _receive_all(socket, num_bytes):
    

    buffer = ''
    buffer_size = 0
    bytes_left = num_bytes
    while buffer_size < num_bytes:
        data = socket.recv(bytes_left)
        delta = len(data)
        buffer_size += delta
        bytes_left -= delta
        buffer += data
    return buffer
643446
def receive(self):
        '''
        
        '''
        try:
            msg = self.sub.recv()
        except zmq.Again as error:
            log.error('Unable to receive messages: %s', error, exc_info=True)
            raise ListenerException(error)
        log.debug('[%s] Received %s', time.time(), msg)
        return msg, ''
804446
def maybe_get_next_message(self):
        
        if self.pending:
            self.ioloop.add_callback(
                self.invoke_consumer, self.pending.popleft())
726625
def _receive_message(self):
        
        while True:
            try:
                if self._socket.getsockopt(zmq.TYPE) == zmq.ROUTER:
                    zmq_identity, msg_bytes = \
                        yield from self._socket.recv_multipart()
                    if msg_bytes == b'':
                        # send ACK for connection probes
                        LOGGER.debug("ROUTER PROBE FROM %s", zmq_identity)
                        self._socket.send_multipart(
                            [bytes(zmq_identity), msg_bytes])
                    else:
                        self._received_from_identity(zmq_identity)
                        self._dispatcher_queue.put_nowait(
                            (zmq_identity, msg_bytes))
                else:
                    msg_bytes = yield from self._socket.recv()
                    self._last_message_time = time.time()
                    self._dispatcher_queue.put_nowait((None, msg_bytes))
                self._get_queue_size_gauge(self.connection).set_value(
                    self._dispatcher_queue.qsize())

            except CancelledError:  # pylint: disable=try-except-raise
                # The concurrent.futures.CancelledError is caught by asyncio
                # when the Task associated with the coroutine is cancelled.
                # The raise is required to stop this component.
                raise
            except Exception as e:  # pylint: disable=broad-except
                LOGGER.exception("Received a message on address %s that "
                                 "caused an error: %s", self._address, e)
1187249
def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]:
        
        approximate_messages = self._receive_buffer.qsize()
        messages = []
        for _ in range(approximate_messages):
            try:
                messages.append(self._receive_buffer.get_nowait())
            except queue.Empty:
                break
        return messages
949068
def receive(self):
        '''
        
        '''
        try:
            msg, addr = self.skt.recvfrom(self.buffer_size)
        except socket.error as error:
            log.error('Received listener socket error: %s', error, exc_info=True)
            raise ListenerException(error)
        log.debug('[%s] Received %s from %s', msg, addr, time.time())
        return msg, addr[0]
310961
def receive(max_len=nil)
      max_len ||= 1024

      begin
        data = @socket.recv(max_len)
      rescue IO::WaitReadable
        @logger.logv 'Retrying receive...'
        IO.select([@socket])
        retry
      rescue Exception => e
        if e.class != 'IOError' && e.message != 'closed stream'
          @logger.log_exception(e, 'EXCEPTION during receive!')
        end
      end

      if (data.nil? || data.empty?)
        @logger.log "Client #{@socket.inspect} disconnected!"
        data = ''
      else
        @logger.log "Received #{data.length} bytes"
      end

      return data
    end
498461
def receive(self):
        
        try:
            itr = 0
            while self.connected:
                
                r, w, e = select.select(
                    (self.sock, ), (), (), 10.0)
                
                if r:
                    message = json.loads(self.recv())
                    
                    if 'fetch' in message:
                        self.fetch_id = message['fetch']
                    
                    if 'failure' in message:
                        raise InvalidFetch(message['failure'])
                    
                    if 'records' in message:
                        if 'added' in message['records']:
                            num = len(message['records']['added'])
                        else:
                            num = len(message['records'])
                        
                        logger.debug('Query returned %s records.', num)
                        if self.max_recv:
                            itr += 1
                        
                    if 'end' in message:
                        logger.debug('Received end message: %s' % message['end'])
                        yield message
                        break
                    
                    yield message
                    if self.max_recv and self.max_recv <= itr:
                        break   

        except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e:
            logger.info('Caught exception in receive: %s -> %s', type(e), str(e))
            if isinstance(e, (SystemExit, InvalidFetch)):
                # propagate SystemExit, InvalidFetch
                raise
        finally:
            if self.connected:
                if self.fetch_id:
                    self.send(json.dumps({'abort': self.fetch_id}))
                self.close()
            
            if self.thread:
                self.event.set()
                while self.thread.isAlive():
                    self.event.wait(1)
            
            logger.info('Closed web socket connection normally.')
1120428
def recv(self, blocking=True):
        """"""
        length = struct.unpack("<I", self.sock.recv(4))[0]
        return self._get_next_obj(length)