Get response from zabbix server, reads from self.socket.

        :type connection: :class:`socket._socketobject`
        :param connection: Socket to read.

        :rtype: dict
        :return: Response from zabbix server or False in case of error.
185513
def _get_response(self, connection):
        

        response_header = self._receive(connection, 13)
        logger.debug('Response header: %s', response_header)

        if (not response_header.startswith(b'ZBXD\x01') or
                len(response_header) != 13):
            logger.debug('Zabbix return not valid response.')
            result = False
        else:
            response_len = struct.unpack('<Q', response_header[5:])[0]
            response_body = connection.recv(response_len)
            result = json.loads(response_body.decode("utf-8"))
            logger.debug('Data received: %s', result)

        try:
            connection.close()
        except Exception as err:
            pass

        return result
892627
def receive(self):
        
        if self._closed:
            raise WebSocketError("Connection is already closed")
        try:
            return self.read_message()
        except UnicodeError as e:
            logger.info('websocket.receive: UnicodeError {}'.format(e))
            self.close(1007)
        except WebSocketError as e:
            logger.info('websocket.receive: WebSocketError {}'.format(e))
            self.close(1002)
        except Exception as e:
            logger.info('websocket.receive: Unknown error {}'.format(e))
            raise e
976246
def readline(self, raise_exception=False):
        
        buf = self.buffer
        if self.socket:
            recv = self.socket.recv
        else:
            recv = lambda bufsize: ''

        while True:
            index = buf.find('\r\n')
            if index >= 0:
                break
            data = recv(4096)
            if not data:
                # connection close, let's kill it and raise
                self.mark_dead('connection closed in readline()')
                if raise_exception:
                    raise _ConnectionDeadError()
                else:
                    return ''

            buf += data
        self.buffer = buf[index+2:]
        return buf[:index]
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
323073
def _server_response_handler(self, response: Dict[str, Any]):
        
        code = response.get("CODE")
        if code == 100:
            if self.debug:
                print("auth succeed")
            self._login_fut.set_result(response)
        if code == 101:
            if self.debug:
                print('pong')
        return True
1187011
def get_response(sock, buffer_size=4096):
    
    response = ""
    extra = ""

    while True:
        try:
            chunk = sock.recv(buffer_size)
            if chunk:
                response += chunk
        except socket.error as e:
            if e.errno not in [errno.EAGAIN, errno.EINTR]:
                raise

        if not response:
            break

        if "\n" in response:
            response, extra = response.split("\n", 1)
            break

    return response, extra
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
1334642
def receive_connection():
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client
651006
def _read_callback(connection_id, data_buffer, data_length_pointer):
    
    wrapped_socket = None
    try:
        wrapped_socket = _connection_refs.get(connection_id)
        if wrapped_socket is None:
            return SecurityConst.errSSLInternal
        base_socket = wrapped_socket.socket

        requested_length = data_length_pointer[0]

        timeout = wrapped_socket.gettimeout()
        error = None
        read_count = 0

        try:
            while read_count < requested_length:
                if timeout is None or timeout >= 0:
                    if not util.wait_for_read(base_socket, timeout):
                        raise socket.error(errno.EAGAIN, 'timed out')

                remaining = requested_length - read_count
                buffer = (ctypes.c_char * remaining).from_address(
                    data_buffer + read_count
                )
                chunk_size = base_socket.recv_into(buffer, remaining)
                read_count += chunk_size
                if not chunk_size:
                    if not read_count:
                        return SecurityConst.errSSLClosedGraceful
                    break
        except (socket.error) as e:
            error = e.errno

            if error is not None and error != errno.EAGAIN:
                data_length_pointer[0] = read_count
                if error == errno.ECONNRESET or error == errno.EPIPE:
                    return SecurityConst.errSSLClosedAbort
                raise

        data_length_pointer[0] = read_count

        if read_count != requested_length:
            return SecurityConst.errSSLWouldBlock

        return 0
    except Exception as e:
        if wrapped_socket is not None:
            wrapped_socket._exception = e
        return SecurityConst.errSSLInternal
858316
def _did_receive_response(self, connection):
        

        if connection.has_timeouted:
            bambou_logger.info("NURESTConnection has timeout.")
            return

        has_callbacks = connection.has_callbacks()
        should_post = not has_callbacks

        if connection.handle_response_for_connection(should_post=should_post) and has_callbacks:
            callback = connection.callbacks['local']
            callback(connection)
75697
def read_response(self):
        ""
        try:
            response = self._parser.read_response()
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout reading from %s:%s" %
                               (self.host, self.port))
        except socket.error:
            self.disconnect()
            e = sys.exc_info()[1]
            raise ConnectionError("Error while reading from %s:%s : %s" %
                                  (self.host, self.port, e.args))
        except:  # noqa: E722
            self.disconnect()
            raise
        if isinstance(response, ResponseError):
            raise response
        return response
747248
private String response(HttpURLConnection connection) throws LightblueHttpClientException {
        try (InputStream responseStream = connection.getInputStream()) {
            return readResponseStream(responseStream, connection);
        } catch (IOException e) {
            return readErrorStream(connection,e);
        }
    }
169068
def connect(self):
        
        try:
            self.sock.connect((self.host, self.port))
            return self.sock
        except socket.error as ex:
            logging.error('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
            raise
        except Exception as ex:
            logging.exception('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
            raise
1082028
def _get_socket(self, sslversion=ssl.PROTOCOL_TLSv1):
        
        err = None
        sock = None
        try:
            for res in socket.getaddrinfo(
                    self.hostname, self.port, 0, socket.SOCK_STREAM):
                af, socktype, proto, canonname, sa = res
                try:
                    sock = socket.socket(af, socktype, proto)
                    sock.settimeout(self.timeout)
                    # Connecting to {self.hostname} at port {self.port}
                    sock.connect(sa)
                except socket.timeout:
                    if sock is not None:
                        sock.close()
                    err = exception.IloConnectionError(
                        "Timeout connecting to %(hostname)s:%(port)d"
                        % {'hostname': self.hostname, 'port': self.port})
                except socket.error:
                    if sock is not None:
                        sock.close()
                    e = sys.exc_info()[1]
                    err = exception.IloConnectionError(
                        "Error connecting to %(hostname)s:%(port)d : %(error)s"
                        % {'hostname': self.hostname, 'port': self.port,
                           'error': str(e)})
        except Exception:
            raise exception.IloConnectionError(
                "Unable to resolve %s" % self.hostname)

        if err is not None:
            raise err

        # wrapping the socket over ssl session
        try:
            return ssl.wrap_socket(sock, ssl_version=sslversion)
        except socket.sslerror:
            e = sys.exc_info()[1]
            msg = (getattr(e, 'reason', None) or
                   getattr(e, 'message', None))
            # Some older iLO s don't support TLSv1, retry with SSLv3
            if ('wrong version number' in msg) and (
                    sslversion == ssl.PROTOCOL_TLSv1):

                return self._get_socket(ssl.PROTOCOL_SSLv3)

            raise exception.IloConnectionError(
                "Cannot establish ssl session with %(hostname)s:%(port)d : "
                "%(error)s" % {'hostname': self.hostname, 'port': self.port,
                               'error': str(e)})
1256809
async def connect(self, connection):
        
        if self._user_connected:
            self._log.info('User is already connected!')
            return

        self._connection = connection
        await self._connect()
        self._user_connected = True
375232
def connection(self):
        
        connection = getattr(self.state, "connection", None)
        if connection is None:
            connection = self.state.connection = pika.BlockingConnection(
                parameters=self.parameters)
            self.connections.add(connection)
        return connection
602124
def _read(self):
        
        raw_response = self.transport.receive()
        response = Packet.parse(raw_response)

        # FIXME
        if response.response_type == Packet.EVENT and response.event_type == "log":
            # queue up any debug log messages, and get next
            self.log_events.append(response)
            # do something?
            self._read()
        else:
            return response