Read bytes from the connection and hand them to the protocol.
		@raises OmapiError:
		@raises socket.error:
768131
def fill_inbuffer(self):
		
		if not self.connection:
			raise OmapiError("not connected")
		try:
			data = self.connection.recv(2048)
		except socket.error:
			self.close()
			raise
		if not data:
			self.close()
			raise OmapiError("connection closed")
		try:
			self.protocol.data_received(data)
		except OmapiSizeLimitError:
			self.close()
			raise
129539
private void readData()
        throws IOException
    {
        while (!isClosed) {
            int code = is.read();

            switch (code) {
                case ' ':
                case '\t':
                case '\n':
                case '\r':
                    break;

                case 'C': {
                    int channel = (is.read() << 8) + is.read();

                    inputReady[channel] = true;
                    return;
                }

                case 'E': {
                    int channel = (is.read() << 8) + is.read();
                    int status = (is.read() << 8) + is.read();

                    inputReady[channel] = true;

                    return;
                }

                case -1:
                    close();
                    return;

                default:
                    // An error in the protocol.  Kill the connection.
                    close();
                    return;
            }
        }

        return;
    }
87720
def receive(bytes)
      response = ""
      loop do
        if bytes <= @receive_buffer.bytesize
          array = @receive_buffer.bytes.to_a
          response = array[0..(bytes - 1)].pack('c*')
          @receive_buffer = array[(bytes)..-1].pack('c*')
          break
        end

        chunk = @connection.read_data
        if chunk.bytesize > 0
          @receive_buffer += chunk
        else
          sleep(0.1)
        end
      end
      @logger.debug("RX: #{unpack(response).inspect}")

      response
    end
543894
def socket_reader(connection: socket, buffer_size: int = 1024):
    
    while connection is not None:
        try:
            buffer = connection.recv(buffer_size)
            # no output
            if not len(buffer):
                raise ConnectionAbortedError
        except ConnectionAbortedError:
            # socket closed
            print('connection aborted')
            connection.close()
            yield None
        except OSError:
            # still operate connection after it was closed
            print('socket closed')
            connection.close()
            yield None
        else:
            yield buffer
203152
def _read_protos(self, size):
        
        _byte = self._read_unpack(size)
        _prot = ETHERTYPE.get(_byte)
        return _prot
1317829
def read()
            size_a = @stream.read 2
            size = Common.decode_u16(size_a)
            data = @stream.read size

            data = MessagePack.unpack data
            class_ = Common.packet_from_id data[0]
            class_.new *data[1][0]
        end
230898
def _read_msg(self):
        """"""

        #
        # NOTE:
        # '_recv_socket(nbytes)' was implemented as
        # 'socket.recv(nbytes, socket.MSG_WAITALL)'
        # but socket.MSG_WAITALL proved not reliable
        #

        def _recv_socket(nbytes):
            """read nbytes bytes from self.socket"""

            #
            # code below is written under the assumption that
            # 'nbytes' is smallish so that the 'while len(buf) < nbytes' loop
            # is entered rarerly
            #
            try:
                buf = self.socket.recv(nbytes)
            except IOError as err:
                raise ConnError(*err.args)

            if not buf:
                raise ShortRead(0, nbytes)

            while len(buf) < nbytes:
                try:
                    tmp = self.socket.recv(nbytes - len(buf))
                except IOError as err:
                    raise ConnError(*err.args)

                if not tmp:
                    if self.verbose:
                        print('ee', repr(buf))
                    raise ShortRead(len(buf), nbytes)

                buf += tmp

            assert len(buf) == nbytes, (buf, len(buf), nbytes)
            return buf

        data = _recv_socket(_FromServerHeader.header_size)
        header = _FromServerHeader(data)
        if self.verbose:
            print('<-', repr(header))

        # error conditions
        if header.version != 0:
            raise MalformedHeader('bad version', header)
        if header.payload > MAX_PAYLOAD:
            raise MalformedHeader('huge payload, unwilling to read', header)

        if header.payload > 0:
            payload = _recv_socket(header.payload)
            if self.verbose:
                print('..', repr(payload))
            assert header.size <= header.payload
            payload = payload[:header.size]
        else:
            payload = bytes()
        return header, payload
1228561
def decode(self, bytes):
        

        self.buffer = bytes
        self._pos = 0

        Packet = identifier.get_packet_from_id(self._read_variunt())

        # unknown packets will be None from the identifier
        if Packet is None:
            return None

        packet = Packet()
        packet.ParseFromString(self.remaining_bytes())
        return packet
449140
def decode(self, bytes):
        
        opcode  = struct.unpack(">H", bytes[0:2])[0]
        nbytes  = struct.unpack("B",  bytes[2:3])[0]
        name   = None
        args   = []

        if opcode in self.opcodes:
            defn = self.opcodes[opcode]
            name = defn.name
            stop = 3

            for arg in defn.argdefns:
                start = stop
                stop  = start + arg.nbytes
                if arg.fixed:
                    pass  # FIXME: Confirm fixed bytes are as expected?
                else:
                    args.append(arg.decode(bytes[start:stop]))

        return self.create(name, *args)
1236257
def read(self, *args, **kwargs):
        
        buf = io.BufferedReader.read(self, *args, **kwargs)
        self.increment(len(buf))
        return buf
1029550
def readBytes(self, size):
        

        # try to satisfy the read from any buffered data
        if self._iobuf:
            if size >= len(self._iobuf):
                res = self._iobuf
                self.buf = None
                return res
            res = self._iobuf[:size]
            self._iobuf = self._iobuf[size:]
            return res

        # We need to initiate a read
        buf = ctypes.create_string_buffer(size)
        olap = OVERLAPPED()
        olap.hEvent = self._waitable

        log("made read buff of size %d", size)

        # ReadFile docs warn against sending in the nread parameter for async
        # operations, so we always collect it via GetOverlappedResultEx
        immediate = ReadFile(self.pipe, buf, size, None, olap)

        if not immediate:
            err = GetLastError()
            if err != ERROR_IO_PENDING:
                self._raise_win_err("failed to read %d bytes" % size, err)

        nread = wintypes.DWORD()
        if not self._get_overlapped_result_ex(
            self.pipe, olap, nread, 0 if immediate else self.timeout, True
        ):
            err = GetLastError()
            CancelIoEx(self.pipe, olap)

            if err == WAIT_TIMEOUT:
                log("GetOverlappedResultEx timedout")
                raise SocketTimeout(
                    "timed out after waiting %dms for read" % self.timeout
                )

            log("GetOverlappedResultEx reports error %d", err)
            self._raise_win_err("error while waiting for read", err)

        nread = nread.value
        if nread == 0:
            # Docs say that named pipes return 0 byte when the other end did
            # a zero byte write.  Since we don't ever do that, the only
            # other way this shows up is if the client has gotten in a weird
            # state, so let's bail out
            CancelIoEx(self.pipe, olap)
            raise IOError("Async read yielded 0 bytes; unpossible!")

        # Holds precisely the bytes that we read from the prior request
        buf = buf[:nread]

        returned_size = min(nread, size)
        if returned_size == nread:
            return buf

        # keep any left-overs around for a later read to consume
        self._iobuf = buf[returned_size:]
        return buf[:returned_size]
495882
def drain(self):
        
        data = self._stream.getvalue()
        if len(data):
            yield from self._protocol.send(data)
        self._stream = io.BytesIO(b'')
1083952
def readn(self, n):
        
        data = ''

        while len(data) < n:
            received = self.sock.recv(n - len(data))

            if not len(received):
                raise socket.error('no data read from socket')

            data += received

        return data
609665
def from_bytes(cls, bitstream, decode_payload=True):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the version
        version = bitstream.read('uint:4')
        if version != packet.version:
            raise ValueError('Provided bytes do not contain an IPv4 packet')

        # Read the header length
        ihl = bitstream.read('uint:4')
        if ihl < 5:
            raise ValueError('Invalid IPv4 header length')

        # Now that we know the length of the header we store it to be able
        # to easily recalculate the header checksum later
        remaining_header_bits = (ihl * 32) - 8
        header = (BitStream('uint:4=4, uint:4=%d' % ihl) +
                  bitstream.peek(remaining_header_bits))

        # Read the type of service
        packet.tos = bitstream.read('uint:8')

        # Read the total length
        total_length = bitstream.read('uint:16')
        if total_length < ihl * 4:
            raise ValueError('Total length is shorter than the header')

        # Read the identification
        packet.identification = bitstream.read('uint:16')

        # Read the flags
        (reserved,
         packet.dont_fragment,
         packet.more_fragments) = bitstream.readlist('3*bool')

        if reserved:
            raise ValueError('Reserved flag must be 0')

        # Read the fragment offset
        packet.fragment_offset = bitstream.read('uint:13')

        # Read the TTL
        packet.ttl = bitstream.read('uint:8')

        # Read the protocol number
        packet.protocol = bitstream.read('uint:8')

        # Read the header checksum
        header_checksum = bitstream.read('uint:16')

        # Set the checksum bits in the header to 0 and re-calculate
        header[80:96] = BitStream(16)
        my_checksum = checksum.ones_complement(header.bytes)

        if my_checksum != header_checksum:
            raise ValueError('Header checksum does not match')

        # Read the source and destination addresses
        packet.source = IPv4Address(bitstream.read('uint:32'))
        packet.destination = IPv4Address(bitstream.read('uint:32'))

        # Read the options
        option_len = (ihl - 5) * 4
        packet.options = bitstream.read('bytes:%d' % option_len)

        # And the rest is payload
        payload_bytes = (total_length) - (ihl * 4)
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        if decode_payload:
            payload_class = protocol_registry.get_type_class(packet.protocol)
            if payload_class:
                packet.payload = payload_class.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
401805
async def _readline(self, timeout: NumType = None):
        
        if self._stream_reader is None or self._stream_writer is None:
            raise SMTPServerDisconnected("Client not connected")

        read_task = asyncio.Task(
            self._stream_reader.readuntil(separator=b"\n"), loop=self._loop
        )
        try:
            line = await asyncio.wait_for(
                read_task, timeout, loop=self._loop
            )  # type: bytes
        except asyncio.LimitOverrunError:
            raise SMTPResponseException(
                SMTPStatus.unrecognized_command, "Line too long."
            )
        except asyncio.TimeoutError as exc:
            raise SMTPTimeoutError(str(exc))
        except asyncio.IncompleteReadError as exc:
            if exc.partial == b"":
                # if we got only an EOF, raise SMTPServerDisconnected
                raise SMTPServerDisconnected("Unexpected EOF received")
            else:
                # otherwise, close our connection but try to parse the
                # response anyways
                self._stream_writer.close()
                line = exc.partial

        return line
916873
def read_bytes(self, length) -> bytes:
        
        value = self.stream.read(length)
        return value
507917
def read(read_len)
      # If we closed the connection, return nil without calling anything again to avoid EOF
      # or other errors
      return nil if @closed

      if @left_to_read
        # We hit the end of what we need to read, if this is a chunked request, then we need to check for the next chunk
        if @left_to_read <= read_len
          data = @socket.read(@left_to_read)
          @total_size += @left_to_read
          @left_to_read = nil
          @read_clfr = true
        # Reading from known buffer still
        else
          @left_to_read -= read_len
          @total_size += read_len
          data = @socket.read(read_len)
        end

      elsif @chunked
        # We finished reading the chunks, read the last 2 to get \r\n out of the way, and then find the next chunk
        if @read_clfr
          @read_clfr = nil
          @socket.read(2)
        end

        data, chunk_read = "", 0
        while true
          # Read first line to get the chunk length
          line = @socket.readline

          len = line.slice(/[0-9a-fA-F]+/) or raise Net::HTTPBadResponse.new("wrong chunk size line: #{line}")
          len = len.hex

          # Nothing left, read off the final \r\n
          if len == 0
            @socket.read(2)
            @socket.close
            @response.instance_variable_set(:@read, true)

            @closed = true
            break
          end

          # Reading this chunk will set us over the buffer amount
          # Read what we can of it (if anything), and send back what we have and queue a read for the rest
          if ( chunk_read + len ) > read_len
            can_read = len - ( ( chunk_read + len ) - read_len )

            @left_to_read = len - can_read
            @total_size += can_read

            data << @socket.read(can_read) if can_read > 0
            break
          # We can just return the chunk as-is
          else
            @total_size += len
            chunk_read += len

            data << @socket.read(len)
            @socket.read(2)
          end
        end

      # If we don't have a content length, then we need to keep reading until we run out of data
      elsif !@content_length
        data = @socket.readline

        @total_size += data.length if data
      end

      # We've finished reading, set this so Net::HTTP doesn't try and read it again
      if !data or data == ""
        @response.instance_variable_set(:@read, true)

        nil
      else
        if data.length >= @total_size and !@chunked
          @response.instance_variable_set(:@read, true)
        end

        if ENCODABLE and @encoding
          data = data.force_encoding(@encoding) if @encoding
          data = data.encode("UTF-8")
        end

        @digest.update(data)
        data
      end

    # Mark as read finished, return the last bits of data (if any)
    rescue EOFError
      @response.instance_variable_set(:@read, true)
      @socket.close
      @closed = true

      if data and data != ""
        @digest.update(data)
        data
      else
        nil
      end
    end