首页 > 代码库 > python-组播
python-组播
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
python-组播
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。