本文整理汇总了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
示例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
示例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)
示例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
示例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
示例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
示例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()
示例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()
示例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:]
示例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)
示例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))
示例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()
示例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
示例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
示例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