1 #!/usr/bin/python 2 #coding=utf-8 3 #发送端 4 import sys,struct,socket 5 from time import sleep 6 7 message="hello" 8 message1="nihao" 9 10 multicast_group=(‘224.3.29.73‘,10003) 11 multicast_group1=(‘224.3.29.74‘,10004) 12 13 sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 14 15 sock.timeout(3) 16 17 ttl=struct.pack(‘b‘,1) #将数字1转换成无符号字符类型.在python中没有这种类型,但是内核需要,所以转换 18 19 sock.setsockopt(socket.IPPROTO_IP,socket.IP_MULTICAST_TTL,ttl) 20 21 try: 22 while 1: 23 sleep(2) 24 sent=sock.sendto(message,multicast_group) 25 sent=sock.sendto(message1,multicast_group1) 26 27 print >>sys.stderr,"waiting to receive" 28 29 try: 30 data,server=sock.recvfrom(1024) 31 except sock.timeout: 32 print >>sys.stderr,"time out ,no more response" 33 break 34 else: 35 print >>sys.stderr,"received %s from %s"%(data,server) 36 finally: 37 print >>sys.stderr,"closing socket" 38 sock.close()
1 #!/usr/bin/python 2 #接收端 3 import socket 4 import sys 5 import struct 6 7 multicast_group = ‘224.3.29.72‘ 8 server_address = (‘‘,10001) 9 10 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 11 12 sock.bind(server_address) 13 14 group = socket.inet_aton(multicast_group) 15 mreq = struct.pack(‘4sL‘,group,socket.INADDR_ANY) 16 sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,mreq) 17 18 while True: 19 print >>sys.stderr,‘\nwaiting to receive message‘ 20 data,address = sock.recvfrom(1024) 21 22 print >>sys.stderr,‘received %s bytes from %s‘%(len(data),data) 23 print >>sys.stderr,‘sending acknowledgement to‘,address 24 sock.sendto(‘gaozhiqiangf‘,address) 25
时间: 2024-10-11 03:30:36