本文整理汇总了Python中socket.recvfrom方法的典型用法代码示例。如果您正苦于以下问题:Python socket.recvfrom方法的具体用法?Python socket.recvfrom怎么用?Python socket.recvfrom使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.recvfrom方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def update(self, timeout = 0):
try:
reads = select.select([self.socket], [], [], timeout)[0]
except ValueError:
# ValueError: file descriptor cannot be a negative integer (-1)
return
for socket in reads:
try:
packet = ReadBootProtocolPacket(*socket.recvfrom(4096))
except OSError:
# OSError: [WinError 10038] An operation was attempted on something that is not a socket
pass
else:
self.received(packet)
for transaction_id, transaction in list(self.transactions.items()):
if transaction.is_done():
transaction.close()
self.transactions.pop(transaction_id)
示例2: _send_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def _send_socket(self, cmd, rtnCmd, ip, port):
socket = self._socket
try:
_LOGGER.debug('Sending to GW {0}'.format(cmd))
self._read_unwanted_data()
socket.settimeout(30.0)
socket.sendto(cmd.encode(), (ip, port))
socket.settimeout(30.0)
data, addr = socket.recvfrom(1024)
if len(data) is not None:
resp = json.loads(data.decode())
_LOGGER.debug('Recieved from GW {0}'.format(resp))
if resp["cmd"] == rtnCmd:
return resp
else:
_LOGGER.error("Response from {0} does not match return cmd".format(ip))
_LOGGER.error(data)
else:
_LOGGER.error("No response from Gateway")
except socket.timeout:
_LOGGER.error("Cannot connect to Gateway")
socket.close()
示例3: _listen_to_msg
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def _listen_to_msg(self):
while self._listening:
if self._mcastsocket is not None:
data, addr = self._mcastsocket.recvfrom(self.SOCKET_BUFSIZE)
try:
data = json.loads(data.decode("ascii"))
cmd = data['cmd']
_LOGGER.debug(format(data))
if cmd == 'heartbeat' and data['model'] == 'gateway':
self.GATEWAY_TOKEN = data['token']
elif cmd == 'report' or cmd == 'heartbeat':
self._queue.put(data)
else:
_LOGGER.error('Unknown multicast data : {0}'.format(data))
except Exception as e:
raise
_LOGGER.error('Cannot process multicast message : {0}'.format(data))
示例4: __grab_data__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def __grab_data__(self, socket):
time.sleep(1)
while self.streaming:
try:
data, address = socket.recvfrom(1024)
jdata = json.loads(data.decode('utf-8'))
self.__refresh_data__(jdata)
except socket.timeout:
logging.error("A timeout occurred while receiving data")
self.streaming = False
示例5: capture
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def capture(self, sock):
""" Capture packets in traffic
param: sock(socket._socketobject): raw socket that listen for traffic
"""
while True:
# socket.recvfrom() method returns tuple object
packet_tuple = sock.recvfrom(65565)
packet_str = packet_tuple[0]
self.packet_parser.parse(self.ip, packet_str)
示例6: __discover_device__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def __discover_device__(self):
if TOBII_DISCOVERY_ALLOWED == False:
logging.error("Device discovery is not available due to a missing dependency (netifaces)")
exit(1)
logging.debug("Looking for a Tobii Pro Glasses 2 device ...")
MULTICAST_ADDR = 'ff02::1'
PORT = 13006
for i in netifaces.interfaces():
if netifaces.AF_INET6 in netifaces.ifaddresses(i).keys():
if "%" in netifaces.ifaddresses(i)[netifaces.AF_INET6][0]['addr']:
if_name = netifaces.ifaddresses(i)[netifaces.AF_INET6][0]['addr'].split("%")[1]
if_idx = socket.getaddrinfo(MULTICAST_ADDR + "%" + if_name, PORT, socket.AF_INET6, socket.SOCK_DGRAM)[0][4][3]
s6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s6.settimeout(30.0)
s6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, if_idx)
s6.bind(('::', PORT))
PORT_OUT = PORT if sys.platform == 'win32' or sys.platform == 'darwin' else PORT + 1
try:
discover_json = '{"type":"discover"}'
s6.sendto(discover_json.encode('utf-8'), (MULTICAST_ADDR, PORT_OUT))
logging.debug("Discover request sent to %s on interface %s " % ( str((MULTICAST_ADDR, PORT_OUT)),if_name) )
logging.debug("Waiting for a reponse from the device ...")
data, address = s6.recvfrom(1024)
jdata = json.loads(data.decode('utf-8'))
logging.debug("From: " + address[0] + " " + str(data))
logging.debug("Tobii Pro Glasses found with address: [%s]" % address[0])
addr = address[0]
if sys.version_info.major == 3 and sys.version_info.minor >= 8:
addr = address[0] + '%' + if_name
return (jdata, addr)
except:
logging.debug("No device found on interface %s" % if_name)
logging.debug("The discovery process did not find any device!")
return (None, None)
示例7: get
# 需要导入模块: import socket [as 别名]
# 或者: from socket import recvfrom [as 别名]
def get(items):
try:
message = json.dumps(items).encode('utf-8') # Take requested data and convert to bytes
socket.sendto(message, (network.ip,network.port)) # Send data to server
data, ip = socket.recvfrom(4000) # Wait for response, create 4000 byte buffer to store response.
data = json.loads(data) # Take response and convert from bytes to string
data = dict(zip(items, data)) # Combine request list with respose list to create dictionary
return data # Return data
except Exception as e:
print(e)
return 1