如何在Python中使用UDP多播发送和接收文件,有标准的图书馆可以这样做吗?,或任何其他标准功能模块?
以下是关于如何使用源代码示例做到这一点的信息:
import socket
import struct
import sys
message = 'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settimeout(0.2)
try:
# Send data to the multicast group
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, multicast_group)
# Look for responses from all recipients
while True:
print >>sys.stderr, 'waiting to receive'
try:
data, server = sock.recvfrom(16)
except socket.timeout:
print >>sys.stderr, 'timed out, no more responses'
break
else:
print >>sys.stderr, 'received "%s" from %s' % (data, server)
finally:
print >>sys.stderr, 'closing socket'
sock.close()