import socket ,struct,time
# 组播地址和端口号
MCAST_GRP = '239.0.0.1'
MCAST_PORT = 8888
# 创建UDP socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# 绑定socket对象到本地端口号
# sock.bind((MCAST_GRP, MCAST_PORT))
# 加入组播组
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) # 使用INADDR_ANY来指定任何网络接口
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# 发送组播消息
message = b'Hello, multicast!'
sock.sendto(message, (MCAST_GRP, MCAST_PORT))
print('aa')
cnt = 0
# 接收组播消息
while True:
message = 'Hello, zym!' +str(cnt)
print(message)
message=message.encode('gbk')
cnt = cnt+1
sock.sendto(message, (MCAST_GRP, MCAST_PORT))
time.sleep(1)
#data, addr = sock.recvfrom(1024)
#print('Received message:', data)
实测wifi环境中1发两收,1s发送一次。接收端的丢包率很严重。