Read data from the connection.  If the request hasn't yet been sent
to the server, send it.
197254
public int read(byte []buf, int offset, int length) throws IOException
  {
    try {
      return readInt(buf, offset, length);
    } catch (IOException e) {
      _isKeepalive = false;
      throw e;
    } catch (RuntimeException e) {
      _isKeepalive = false;
      throw e;
    }
  }
234965
def on_connect(self, connection):
        
        self._sock = connection._sock
        self._buffer = SocketBuffer(self._sock, self.socket_read_size)        
        if connection.decode_responses:
            self.encoding = connection.encoding
350617
def read(self, length):
        
        data = bytearray()
        while len(data) != length:
            data += self.sock.recv((length - len(data)))
            if not data:
                raise ConnectionError('Connection unexpectedly closed.')
        return data
358790
def _send_request(self, request, **kwargs):
        """"""
        log.debug(LOG_CHECK, "Send request %s with %s", request, kwargs)
        log.debug(LOG_CHECK, "Request headers %s", request.headers)
        self.url_connection = self.session.send(request, **kwargs)
        self.headers = self.url_connection.headers
        self._add_ssl_info()
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.')
831977
def send(self, request):
        
        self._logger.debug('Opening connection')
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.connect((self._host, self._port))
        talk = SocketTalk(sock, encode=self._encode)

        self._logger.debug('Sending action %s' % request.action)
        if not talk.put(request.action):
            self._logger.error('Failed to send action %s' % request.action)
            return None

        if request.key is not None:
            self._logger.debug('Sending key %s' % request.key)
            if not talk.put(request.key):
                self._logger.error('Failed to send key %s' % request.key)
                return None

        if request.value is not None:
            self._logger.debug('Sending value')
            if not talk.put(request.value):
                self._logger.error('Failed to send value')
                return None

        self._logger.debug('Receiving status')
        response = talk.get()
        if not response:
            self._logger.error('Failed to receive status')
            return None
        self._logger.debug('Status response = %s' % response)

        if request.action in ('get', 'size', 'keys') and response == 'ok':
            self._logger.debug('Receiving value')
            response = talk.get()
            if not response:
                self._logger.error('Failed to receive value')
                return None

        if request.action in ('keys',):
            response = pickle.loads(response)

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

        return response
572396
def _send(self, payload):

        '''
            
        '''

        if not self.connection:
            self._connect()

        # Send the payload, adding a newline to the end
        self.connection.send(payload + '\n')

        # Read 256 bytes off the socket and check the
        # status that returned.
        try:
            data = self.connection.recv(256)

        except socket.timeout, e:
            print 'Failed to read response in a timely manner to determine the status.'
            return False

        if data.split('\n')[1] == 'FAIL':
            print 'Failed to send payload: {payload}'.format(payload = payload)
            return False

        return True
85173
async def read(self) -> bytes:
        """"""
        if self._body is None:
            try:
                self._body = await self.content.read()
                for trace in self._traces:
                    await trace.send_response_chunk_received(self._body)
            except BaseException:
                self.close()
                raise
        elif self._released:
            raise ClientConnectionError('Connection closed')

        return self._body
606603
public function read()
    {
        $data = @fread($this->stream, 30000);

        if($data === false) return;
        $this->buffer .= $data;

        if(!is_null($this->status)) return;
        if(strlen($this->buffer) < 4) return;
        $end = strpos($this->buffer, "\r\n\r\n", 4);
        if($end === false) return;

        list($request, $headers) = $this->parse_header(substr($this->buffer, 0, $end));
        list($version, $status, $phrase) = explode(' ', $request, 3);
        $this->status = $status;
        $this->response_length = isset($headers['content-length'])? (int)$headers['content-length'][0] : 0;
    }
363451
def read(self):
        ''''''
        # We'll check all living connections
        connections = [c for c in self.connections() if c.alive()]

        if not connections:
            # If there are no connections, obviously we return no messages, but
            # we should wait the duration of the timeout
            time.sleep(self._timeout)
            return []

        # Not all connections need to be written to, so we'll only concern
        # ourselves with those that require writes
        writes = [c for c in connections if c.pending()]
        try:
            readable, writable, exceptable = select.select(
                connections, writes, connections, self._timeout)
        except exceptions.ConnectionClosedException:
            logger.exception('Tried selecting on closed client')
            return []
        except select.error:
            logger.exception('Error running select')
            return []

        # If we returned because the timeout interval passed, log it and return
        if not (readable or writable or exceptable):
            logger.debug('Timed out...')
            return []

        responses = []
        # For each readable socket, we'll try to read some responses
        for conn in readable:
            try:
                for res in conn.read():
                    # We'll capture heartbeats and respond to them automatically
                    if (isinstance(res, Response) and res.data == HEARTBEAT):
                        logger.info('Sending heartbeat to %s', conn)
                        conn.nop()
                        logger.debug('Setting last_recv_timestamp')
                        self.last_recv_timestamp = time.time()
                        continue
                    elif isinstance(res, Error):
                        nonfatal = (
                            exceptions.FinFailedException,
                            exceptions.ReqFailedException,
                            exceptions.TouchFailedException
                        )
                        if not isinstance(res.exception(), nonfatal):
                            # If it's not any of the non-fatal exceptions, then
                            # we have to close this connection
                            logger.error(
                                'Closing %s: %s', conn, res.exception())
                            self.close_connection(conn)
                    responses.append(res)
                    logger.debug('Setting last_recv_timestamp')
                    self.last_recv_timestamp = time.time()
            except exceptions.NSQException:
                logger.exception('Failed to read from %s', conn)
                self.close_connection(conn)
            except socket.error:
                logger.exception('Failed to read from %s', conn)
                self.close_connection(conn)

        # For each writable socket, flush some data out
        for conn in writable:
            try:
                conn.flush()
            except socket.error:
                logger.exception('Failed to flush %s', conn)
                self.close_connection(conn)

        # For each connection with an exception, try to close it and remove it
        # from our connections
        for conn in exceptable:
            self.close_connection(conn)

        return responses
704424
def read(self):
        """"""
        data = bytearray()
        while True:
            incoming_bytes = self.comport.inWaiting()
            if incoming_bytes == 0:
                break
            else:
                content = self.comport.read(size=incoming_bytes)
                data.extend(bytearray(content))
        return data
582424
def _data(self, received_data):
        
        if self.listener.on_data(received_data) is False:
            self.stop()
            raise ListenerError(self.listener.connection_id, received_data)
128462
async def send_data(self):
        """"""
        self.connection._ensure_alive()
        conn = self.connection

        try:
            await self._open_file()
            with self._file_object:
                chunk_size = MAX_PACKET_LEN
                while True:
                    chunk = await self._file_read(chunk_size)
                    if not chunk:
                        break
                    # TODO: consider drain data
                    conn.write_packet(chunk)
        except asyncio.CancelledError:
            self.connection._close_on_cancel()
            raise
        finally:
            # send the empty packet to signify we are done sending data
            conn.write_packet(b"")
1179408
protected void read() throws Exception {
    InputStream is = socket.getInputStream();
    while (is.available() > 0) {
      byte[] bytes = new byte[1024 * 1024];
      int read = is.read(bytes);
      byte[] actuallyRead = new byte[read];
      System.arraycopy(bytes, 0, actuallyRead, 0, read);
      pushInput(actuallyRead);
    }
  }
507520
private void sendRequest(Object request, ContextualFuture future) {
    if (open && connection.open) {
      long requestId = ++this.requestId;
      futures.put(requestId, future);
      connection.handleRequest(requestId, request);
    } else {
      future.context.executor().execute(() -> future.completeExceptionally(new ConnectException("connection closed")));
    }

    if (request instanceof ReferenceCounted) {
      ((ReferenceCounted<?>) request).release();
    }
  }
945628
protected Response request (String req)
        throws IOException
    {
        System.err.println("REQ:" + req);

        // send the request to the server
        _out.println(req);
        _out.flush();

        // now read the response
        String rspstr = _in.readLine();
        // if they closed the connection on us, we should deal
        if (rspstr == null) {
            throw new EOFException();
        }
        System.err.println("RSP:" + rspstr);

        // parse the response
        Response rsp = new Response();
        String codestr = rspstr;

        // assume the response is just a code unless we see a space
        int sidx = rspstr.indexOf(" ");
        if (sidx != -1) {
            codestr = rspstr.substring(0, sidx);
            rsp.message = rspstr.substring(sidx+1);
        }

        try {
            rsp.code = Integer.parseInt(codestr);
        } catch (NumberFormatException nfe) {
            rsp.code = 599;
            rsp.message = "Unparseable response";
        }

        return rsp;
    }
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