我想知道是否可以通过创建一个可以从两个地址获取数据的套接字来使用一个套接字,而无需使用多线程(创建几个套接字)来绑定多个组播地址。 / p>
我的代码如下:
import socket
import struct
import time
MCAST_GRP2 = '239.0.1.105'
MCAST_GRP = '239.0.1.104'
MCAST_PORT = 12345
IS_ALL_GROUPS = True
#scan time in seconds
SCAN_TIME = 10
#sampling time in seconds
SAMPLING_TIME = 1
bufferUDP = 2048
totalSize = 0
bitrateList = []
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
# on this port, receives ALL multicast groups
sock.bind(("", MCAST_PORT))
sock2.bind(("", MCAST_PORT))
else:
# on this port, listen ONLY to MCAST_GRP
sock.bind((MCAST_GRP, MCAST_PORT))
sock2.bind((MCAST_GRP2, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
mreq2 = struct.pack("4sl", socket.inet_aton(MCAST_GRP2), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock2.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq2)
print("_____.:| Starting analysis of multicasts! |:._____\n")
for x in range(SCAN_TIME):
stop = time.time() + SAMPLING_TIME
while (time.time()<stop):
totalSize += len(sock.recv(bufferUDP)) + len(sock2.recv(bufferUDP))
bitrateList.append(totalSize)
print(bitrateList[x]*8/(1000000))
totalSize = 0
bitrateList.pop(0)
txtfile = open("Bitrate_history_ip_{}.txt".format("TESTTT"),"w+")
for x in range(SCAN_TIME-1):
bitrateList[x] = bitrateList[x]*8/(1000000)
txtfile.write("{}.Bitrate was equal to: {} Mbps\n".format(x+1,bitrateList[x]))
txtfile.write("Maximum bitrate value was: {} Mbps\n".format(max(bitrateList)))
txtfile.write("Minimum bitrate value was: {} Mbps\n".format(min(bitrateList)))
print('End of test')
time.sleep(5)
并且基于:
答案 0 :(得分:2)
..只需创建一个套接字即可从两个地址获取数据
一个人不能将一个套接字绑定到多个IP地址。
一个人仍然可以并行处理多个套接字,而无需多个线程或多个进程。这是通过基于事件的体系结构和非阻塞套接字完成的,有关更多详细信息,请参见Python文档中的Non-blocking Sockets。