Reads a complete response packet from the server
161611
def _read_response(self):
    
    result = self.buf.read_line().decode("utf-8")
    if not result:
      raise NoResponseError("No response received from server.")

    msg = self._read_message()
    if result != "ok":
      raise InvalidResponseError(msg)

    return msg
812313
def read(self):
        ""
        status = gpscommon.read(self)
        if status <= 0:
            return status
        if self.response.startswith("{") and self.response.endswith("}\r\n"):
            self.unpack(self.response)
            self.__oldstyle_shim()
            self.newstyle = True
            self.valid |= PACKET_SET
        elif self.response.startswith("GPSD"):
            self.__oldstyle_unpack(self.response)
            self.valid |= PACKET_SET
        return 0
757019
def read(self):
        ""
        if self.verbose > 1:
            sys.stderr.write("poll: reading from daemon...\n")
        eol = self.linebuffer.find('\n')
        if eol == -1:
            frag = self.sock.recv(4096)
            self.linebuffer += frag
            if self.verbose > 1:
                sys.stderr.write("poll: read complete.\n")
            if not self.linebuffer:
                if self.verbose > 1:
                    sys.stderr.write("poll: returning -1.\n")
                # Read failed
                return -1
            eol = self.linebuffer.find('\n')
            if eol == -1:
                if self.verbose > 1:
                    sys.stderr.write("poll: returning 0.\n")
                # Read succeeded, but only got a fragment
                return 0
        else:
            if self.verbose > 1:
                sys.stderr.write("poll: fetching from buffer.\n")

        # We got a line
        eol += 1
        self.response = self.linebuffer[:eol]
        self.linebuffer = self.linebuffer[eol:]

        # Can happen if daemon terminates while we're reading.
        if not self.response:
            return -1
        if self.verbose:
            sys.stderr.write("poll: data is %s\n" % repr(self.response))
        self.received = time.time()
        # We got a \n-terminated line
        return len(self.response)
570201
void readStatusResponse() throws SshException, PublicKeySubsystemException {

		ByteArrayReader msg = new ByteArrayReader(nextMessage());

		try {

			msg.readString();
			int status = (int) msg.readInt();
			String desc = msg.readString();

			if (status != PublicKeySubsystemException.SUCCESS) {
				throw new PublicKeySubsystemException(status, desc);
			}
		} catch (IOException ex) {
			throw new SshException(ex);
		} finally {
			try {
				msg.close();
			} catch (IOException e) {
			}
		}
	}
892759
def read_request_headers(self):
        """"""
        # then all the http headers
        try:
            self.header_reader(self.rfile, self.inheaders)
        except ValueError as ex:
            self.simple_response('400 Bad Request', ex.args[0])
            return False

        mrbs = self.server.max_request_body_size

        try:
            cl = int(self.inheaders.get(b'Content-Length', 0))
        except ValueError:
            self.simple_response(
                '400 Bad Request',
                'Malformed Content-Length Header.',
            )
            return False

        if mrbs and cl > mrbs:
            self.simple_response(
                '413 Request Entity Too Large',
                'The entity sent with the request exceeds the maximum '
                'allowed bytes.',
            )
            return False

        # Persistent connection support
        if self.response_protocol == 'HTTP/1.1':
            # Both server and client are HTTP/1.1
            if self.inheaders.get(b'Connection', b'') == b'close':
                self.close_connection = True
        else:
            # Either the server or client (or both) are HTTP/1.0
            if self.inheaders.get(b'Connection', b'') != b'Keep-Alive':
                self.close_connection = True

        # Transfer-Encoding support
        te = None
        if self.response_protocol == 'HTTP/1.1':
            te = self.inheaders.get(b'Transfer-Encoding')
            if te:
                te = [x.strip().lower() for x in te.split(b',') if x.strip()]

        self.chunked_read = False

        if te:
            for enc in te:
                if enc == b'chunked':
                    self.chunked_read = True
                else:
                    # Note that, even if we see "chunked", we must reject
                    # if there is an extension we don't recognize.
                    self.simple_response('501 Unimplemented')
                    self.close_connection = True
                    return False

        # From PEP 333:
        # "Servers and gateways that implement HTTP 1.1 must provide
        # transparent support for HTTP 1.1's "expect/continue" mechanism.
        # This may be done in any of several ways:
        #   1. Respond to requests containing an Expect: 100-continue request
        #      with an immediate "100 Continue" response, and proceed normally.
        #   2. Proceed with the request normally, but provide the application
        #      with a wsgi.input stream that will send the "100 Continue"
        #      response if/when the application first attempts to read from
        #      the input stream. The read request must then remain blocked
        #      until the client responds.
        #   3. Wait until the client decides that the server does not support
        #      expect/continue, and sends the request body on its own.
        #      (This is suboptimal, and is not recommended.)
        #
        # We used to do 3, but are now doing 1. Maybe we'll do 2 someday,
        # but it seems like it would be a big slowdown for such a rare case.
        if self.inheaders.get(b'Expect', b'') == b'100-continue':
            # Don't use simple_response here, because it emits headers
            # we don't want. See
            # https://github.com/cherrypy/cherrypy/issues/951
            msg = self.server.protocol.encode('ascii')
            msg += b' 100 Continue\r\n\r\n'
            try:
                self.conn.wfile.write(msg)
            except socket.error as ex:
                if ex.args[0] not in errors.socket_errors_to_ignore:
                    raise
        return True
333284
def read_all(self) -> str:
        
        try:
            buffered_bytes = self.bytes_buffer.getvalue()
            if buffered_bytes is None:
                return ''

            return buffered_bytes.decode(self.source_encoding)
        except Exception as err:
            return 'Redirect Buffer Error: {}'.format(err)
816580
def _read_response(self):
        
        try:
            line = self.readline()
        except RuntimeError:
            Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'})
            return -1
        if line:
            if self.store_traces:
                self.traces.append(line)
                self.response_traces.append(line)
            EventObject(EventTypes.DUT_LINE_RECEIVED, self, line)
            match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line)
            if match:
                self.logger.debug(line, extra={'type': '<<<'})
            else:
                self.logger.info(line, extra={'type': '<--'})

            retcode = self.check_retcode(line)
            if retcode is not None:
                resp = CliResponse()
                resp.retcode = retcode
                resp.traces = self.response_traces
                resp.lines = self.response_traces
                self.response_traces = []
                return resp
        return None
639800
private Response readResponse() throws IOException {
		Response response = new Response();
		response.setResponseCode(connection.getResponseCode());
		response.setResponseMessage(connection.getResponseMessage());
		response.setHeaders(connection.getHeaderFields());
		try {
			response.setBody(getStringFromStream(connection.getInputStream()));
		} catch (IOException e) {
			response.setBody(getStringFromStream(connection.getErrorStream()));
		}
		return response;
	}
884693
def build_response_packet
      rpacket = Packet::Source.new
      total_size = 0
      request_id = 0
      type = 0
      response = ""
      message = ""
      message2 = ""

      tmp = @socket.recv(4)
      if tmp.nil?
        return nil
      end
      size = tmp.unpack("V1")
      tmp = @socket.recv(size[0])
      request_id, type, message, message2 = tmp.unpack("V1V1a*a*")
      total_size = size[0]
    
      rpacket.packet_size = total_size
      rpacket.request_id = request_id
      rpacket.command_type = type
    
      # strip nulls (this is actually the end of string1 and string2)
      message.sub! /\x00\x00$/, ""
      message2.sub! /\x00\x00$/, ""
      rpacket.string1 = message
      rpacket.string2 = message2
      return rpacket
    end
127150
private byte[] readResponse(URLConnection connection) throws RpcException {
        byte[] resBytes;
        InputStream in = null;
        HttpURLConnection httpconnection = (HttpURLConnection) connection;
        try {
            if (httpconnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                in = httpconnection.getInputStream();
            } else {
                if (httpconnection.getContentType()
                        .equals(serializeHandler.getProtocol().getName())
                        && httpconnection.getErrorStream() != null) {
                    in = httpconnection.getErrorStream();
                } else {
                    in = httpconnection.getInputStream();
                }
            }
            int len = httpconnection.getContentLength();
            if (len <= 0) {
                throw new RpcException("Response data length should not be zero");
            }
            resBytes = ByteUtil.readStream(in, len);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Read " + resBytes.length + " bytes response done");
            }
        } catch (IOException e) {
            throw new RpcException("Rpc read response from server has IO problems - "
                    + e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("Close read response connection error");
                }
            }
        }
        return resBytes;
    }
655791
def _get_response(self):
        
        try:
            self._open_connection()
            if self.connection is None:
                # The connection wasn't opened, which means we're deferring a reconnection attempt.
                # Raise a socket.error, so we'll return the same server_disconnected message as we
                # do below.
                raise socket.error('Delaying reconnection attempt')

            header = self._read_socket(self.HEADER_SIZE)
            (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque,
             cas) = struct.unpack(self.HEADER_STRUCT, header)

            assert magic == self.MAGIC['response']

            extra_content = None
            if bodylen:
                extra_content = self._read_socket(bodylen)

            return (magic, opcode, keylen, extlen, datatype, status, bodylen,
                    opaque, cas, extra_content)
        except socket.error as e:
            self._connection_error(e)

            # (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content)
            message = str(e)
            return (self.MAGIC['response'], -1, 0, 0, 0, self.STATUS['server_disconnected'], 0, 0, 0, message)
973780
def read_body(response, max_bytes=None):
    """"""
    finished = Deferred()
    response.deliverBody(TruncatingReadBodyProtocol(
        response.code, response.phrase, finished, max_bytes))
    return finished
1321489
def _read(self):
        
        line = ''
        finished = False
        while not finished:
            char = self._socket.recv(1)
            if char == '':
                return ''
            elif char == '\r':
                continue
            elif char == '\n':
                finished = True
                continue
            else:
                line = line + char
        logger.debug('Server sent: ' + line.rstrip())
        return line
101830
def _fetch(self):
        
        if self.closed():
            raise self.Error("Failed to read from closed connection {!r}".format(self.server.address))
        if self.defunct():
            raise self.Error("Failed to read from defunct connection {!r}".format(self.server.address))
        if not self.responses:
            return 0, 0

        self._receive()

        details, summary_signature, summary_metadata = self._unpack()

        if details:
            log_debug("[#%04X]  S: RECORD * %d", self.local_port, len(details))  # TODO
            self.responses[0].on_records(details)

        if summary_signature is None:
            return len(details), 0

        response = self.responses.popleft()
        response.complete = True
        if summary_signature == b"\x70":
            log_debug("[#%04X]  S: SUCCESS %r", self.local_port, summary_metadata)
            response.on_success(summary_metadata or {})
        elif summary_signature == b"\x7E":
            self._last_run_statement = None
            log_debug("[#%04X]  S: IGNORED", self.local_port)
            response.on_ignored(summary_metadata or {})
        elif summary_signature == b"\x7F":
            self._last_run_statement = None
            log_debug("[#%04X]  S: FAILURE %r", self.local_port, summary_metadata)
            response.on_failure(summary_metadata or {})
        else:
            self._last_run_statement = None
            raise ProtocolError("Unexpected response message with signature %02X" % summary_signature)

        return len(details), 1
67549
protected boolean readPacket ()
        throws IOException
    {
        int result;
        while ((result = _stream.packetout(_packet)) != 1) {
            if (result == 0 && !readPage()) {
                return false;
            }
        }
        return true;
    }
88777
private function readPacket()
    {
        //get packet size.
        $size_data = fread($this->socket, 4);
        $size_pack = unpack('V1size', $size_data);
        $size = $size_pack['size'];

        // if size is > 4096, the response will be in multiple packets.
        // this needs to be address. get more info about multi-packet responses
        // from the RCON protocol specification at
        // https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
        // currently, this script does not support multi-packet responses.

        $packet_data = fread($this->socket, $size);
        $packet_pack = unpack('V1id/V1type/a*body', $packet_data);

        return $packet_pack;
    }
1256760
@Override
    public ByteBuffer read(ByteBuffer receiveBuffer) throws IOException {
        if (!doHandshake(receiveBuffer))
            return null;

        if (!initialHSComplete)
            throw new IllegalStateException("The initial handshake is not complete.");

        if (log.isDebugEnabled()) {
            log.debug("session {} read data status -> {}, initialHSComplete -> {}", session.getSessionId(),
                    session.isOpen(), initialHSComplete);
        }

        merge(receiveBuffer);
        if (!receivedPacketBuf.hasRemaining()) {
            return null;
        }

        needIO:
        while (true) {
            SSLEngineResult result = unwrap();

            if (log.isDebugEnabled()) {
                log.debug("Session {} read data result -> {}, receivedPacketBuf -> {}, appBufSize -> {}",
                        session.getSessionId(), result.toString().replace('\n', ' '),
                        receivedPacketBuf.remaining(), receivedAppBuf.remaining());
            }

            switch (result.getStatus()) {
                case BUFFER_OVERFLOW: {
                    resizeAppBuffer();
                    // retry the operation.
                }
                break;
                case BUFFER_UNDERFLOW: {
                    int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                    if (receivedPacketBuf.remaining() >= packetBufferSize) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }
                case OK: {
                    if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                        doTasks();
                    }
                    if (receivedPacketBuf.hasRemaining()) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }

                case CLOSED: {
                    log.info("Session {} read data failure. SSLEngine will close inbound", session.getSessionId());
                    closeInbound();
                }
                break needIO;

                default:
                    throw new SecureNetException(StringUtils.replace("Session {} SSLEngine read data exception. status -> {}",
                            session.getSessionId(), result.getStatus()));
            }
        }

        return getReceivedAppBuf();
    }