当前位置: 首页>>代码示例>>Python>>正文


Python socket.recv方法代码示例

本文整理汇总了Python中socket.socket.recv方法的典型用法代码示例。如果您正苦于以下问题:Python socket.recv方法的具体用法?Python socket.recv怎么用?Python socket.recv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socket.socket的用法示例。


在下文中一共展示了socket.recv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _is_client_request_ssl

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def _is_client_request_ssl(cls, socket_: socket.socket) -> bool:
        while True:
            original_timeout = socket_.gettimeout()
            socket_.setblocking(False)

            try:
                data = socket_.recv(3, socket.MSG_PEEK)
            except OSError as error:
                if error.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
                    yield from asyncio.sleep(0.01)
                else:
                    raise
            else:
                break
            finally:
                socket_.settimeout(original_timeout)

        _logger.debug('peeked data %s', data)
        if all(ord('A') <= char_code <= ord('Z') for char_code in data):
            return False
        else:
            return True
开发者ID:Super-Rad,项目名称:wpull,代码行数:24,代码来源:server.py

示例2: __demodulate

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def __demodulate(self, connection: socket.socket):
        connection.settimeout(0.1)
        time.sleep(self.TIMEOUT)

        total_data = []
        while True:
            try:
                data = connection.recv(65536)
                if data:
                    total_data.append(data)
                else:
                    break
            except socket.timeout:
                break

        if len(total_data) == 0:
            logger.error("Did not receive any data from socket.")

        arr = np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64))
        signal = Signal("", "")
        signal._fulldata = arr
        pa = ProtocolAnalyzer(signal)
        pa.get_protocol_from_signal()
        return pa.plain_bits_str
开发者ID:jopohl,项目名称:urh,代码行数:26,代码来源:test_simulator.py

示例3: prepare_socket_for_tls_handshake

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Grab the banner
        if self.SHOULD_WAIT_FOR_SERVER_BANNER:
            sock.recv(2048)

        # Send Start TLS
        sock.send(self.START_TLS_CMD)
        if self.START_TLS_OK not in sock.recv(2048):
            raise StartTlsError(self.ERR_NO_STARTTLS)
开发者ID:nabla-c0d3,项目名称:sslyze,代码行数:11,代码来源:tls_wrapped_protocol_helpers.py

示例4: addNewNode

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def addNewNode(s : socket.socket, orderNode):
    global lockCount
    global lockLst, eps, numNode, k, evnValidate, nodeRecv

    try:
        #receive name of the node
        dataRecv = s.recv(1024).decode()
        addNetworkIn(len(dataRecv))
        try:
            if (dataRecv != ''):
                arg = parser.parse_args(dataRecv.lstrip().split(' '))
                nameNode = arg.name[0]
                if (numNode == 0):
                    numNode = arg.num_node[0]
                    for i in range(numNode):
                        nodeRecv.append(False)
        except socket.error as e:
            print('Error: ' + str(e))
            return

        lockLst.acquire()
        lstSock.append(s)
        lstName.append(nameNode)
        lockLst.release()

        if (orderNode == NUMBER_NODE):
            evnInitComplete.set()

    except socket.error:
        pass
开发者ID:quanglys,项目名称:BPA,代码行数:32,代码来源:CoorNode.py

示例5: _recv

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def _recv(sock: socket.socket, size: int) -> bytes:
    """Secondary function to receive a specified amount of data."""
    message = b''
    while len(message) < size:
        packet = sock.recv(size - len(message))
        if not packet:
            sock.close()
            raise OSError("Nothing else to read from socket")
        message += packet
    return message
开发者ID:skinnersBoxy,项目名称:crossword,代码行数:12,代码来源:wrapper.py

示例6: do_handshake

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def do_handshake(client: socket):
    """Get a client socket and do the handshake of it.

    This method receives a client socket that simulates a switch on the
    network and does the OpenFlow handshake process with a running controller
    on the network.

    Args:
        client (socket): a socket object connected to the controller.

    Returns:
        The client with the handshake process done.

    """
    # -- STEP 1: Send Hello message
    client.send(Hello(xid=3).pack())

    # -- STEP 2: Wait for Hello response
    binary_packet = b''
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 3: Wait for features_request message
    binary_packet = b''
    # len() < 8 here because we just expect a Hello as response
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 4: Send features_reply to the controller
    basedir = os.path.dirname(os.path.abspath(__file__))
    raw_dir = os.path.join(basedir, 'raw')
    message = None
    with open(os.path.join(raw_dir, 'features_reply.cap'), 'rb') as file:
        message = file.read()
    client.send(message)

    return client
开发者ID:kytos,项目名称:kyco,代码行数:43,代码来源:helper.py

示例7: handlerequest

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def handlerequest(clientsocket: socket.socket):
    conn = connecttodb()
    cursor = conn.cursor()
    tagid = bytes.decode(clientsocket.recv(3))
    query = 'select * from tagdata where id={0}'.format(tagid)
    cursor.execute(query)
    s=[]
    for (id, location, officehours, otherinfo, description) in cursor:
        s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description]
        s.insert(0, str(len(''.join(s)))+',')
    clientsocket.send(bytes(''.join(s),encoding='utf8'))
    clientsocket.close()
开发者ID:savanakbari,项目名称:PhysicalWeb,代码行数:14,代码来源:requesthandler.py

示例8: workWithUser

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def workWithUser(s : socket.socket):
    global parser
    global bUserConnect
    bUserConnect = True
    try:
        while 1:
            dataRecv = s.recv(1024).decode()
            if (dataRecv == ''):
                return
    except socket.error:
        return
    finally:
        bUserConnect = False
        s.close()
开发者ID:quanglys,项目名称:BPA,代码行数:16,代码来源:CoorNode.py

示例9: recv

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def recv(self, skt: socket.socket, nbytes: int, buf: bytes) -> Tuple[bytes, bytes]:
        while len(buf) < nbytes:
            data: bytes = b''
            try:
                data = skt.recv(max(nbytes - len(buf), 4096))
            except socket.timeout:
                logging.error("error: recv socket.timeout")
            except Exception as e:
                logging.error(f'error: recv exception: {e!s}')

            if data == b'':
                return b'', b''
            buf += data

        return buf[:nbytes], buf[nbytes:]
开发者ID:couchbase,项目名称:couchbase-cli,代码行数:17,代码来源:pump_mc.py

示例10: _recv_exact

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def _recv_exact(self, sock : socket.socket, num_bytes : int) -> bytes:
        """Receive an exact number of bytes from a socket. This is
        a wrapper around sock.recv() that can return less than the number
        of requested bytes.

        Args:
            sock (socket): Socket to receive data from.
            num_bytes (int): Number of bytes that will be returned.
        """
        bufs = []
        while num_bytes > 0:
            b = sock.recv(num_bytes)
            if len(b) == 0:
                break
            num_bytes -= len(b)
            bufs.append(b)
        return b''.join(bufs)
开发者ID:Opendigitalradio,项目名称:ODR-DabMod,代码行数:19,代码来源:Measure.py

示例11: _receive_message_size

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
    def _receive_message_size(self, sock: socket.socket):

        message_size_chunks = []
        bytes_received = 0

        while bytes_received < self._header_size:
            chunk = sock.recv(
                min(
                    self._header_size - bytes_received,
                    self._header_size
                )
            )
            if chunk == b'':
                raise RuntimeError("JSONSocket: socket broken")
            message_size_chunks.append(chunk.decode('utf-8'))
            bytes_received += len(chunk)

        return int(''.join(message_size_chunks))
开发者ID:strangedev,项目名称:NEAT_PyGenetics,代码行数:20,代码来源:JSONSocket.py

示例12: call

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
 def call(self, *args, **kwargs):
     """
     Remote call.
     """
     socket = Socket(AF_INET, SOCK_STREAM)
     socket.connect(self.address)
     try:
         method = Document()
         method.name = self.name
         method.args = args
         method.kwargs = kwargs
         socket.send(method.dump())
         reply = socket.recv(4096)
         result = Document()
         result.load(reply)
         return result
     finally:
         socket.close()
开发者ID:darinlively,项目名称:gofer,代码行数:20,代码来源:manager.py

示例13: get_page

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def get_page(server_address, request_string):
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
		client_socket.connect((server_address, REMOTE_PORT))

		client_socket.send(request_string.encode())

		reply = bytes()
		while True:
			part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore")
			# print part_body
			if not len(part_body):
				break
			reply += part_body

	finally:
		client_socket.close()

	return reply
开发者ID:shenaishiren,项目名称:computer-network-a-top-approach,代码行数:21,代码来源:web-proxy.py

示例14: receive

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def receive(sock: socket.socket) -> Any:
    """Receive JSON data from a socket until EOF.

    Raise a subclass of OSError if there's a socket exception.

    Raise OSError if the data received is not valid JSON or if it is
    not a dict.
    """
    bdata = bytearray()
    while True:
        more = sock.recv(100000)
        if not more:
            break
        bdata.extend(more)
    if not bdata:
        raise OSError("No data received")
    try:
        data = json.loads(bdata.decode('utf8'))
    except Exception:
        raise OSError("Data received is not valid JSON")
    if not isinstance(data, dict):
        raise OSError("Data received is not a dict (%s)" % str(type(data)))
    return data
开发者ID:greatmazinger,项目名称:mypy,代码行数:25,代码来源:dmypy_util.py

示例15: socket_receive

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import recv [as 别名]
def socket_receive(sock: socket.socket, bufsize: int = BUFFERSIZE) -> str:
    # return socket.recv(bufsize)  # Python 2
    return sock.recv(bufsize).decode("ascii")  # Python 3
开发者ID:RudolfCardinal,项目名称:whisker-python-client,代码行数:5,代码来源:socket.py


注:本文中的socket.socket.recv方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。