标签:udp 广播 python recvfrom sendto
最近状态神勇,头脑清晰,趁此良机,多多学习,多多看书,把以前看不懂的地方重新看了下,收获匪浅,现把两个简单的小例子献给大家:
先是一个简单的UDP广播接收的小服务器,使用UDP广播,需要注意下协议的使用,已经最最重要的socket选项的设置,设置为传说中的“socket.SO_BROADCAST”,不需要有监听,接收客户端的消息使用recvfrom,发送消息使用sendto:
代码如下:
!/usr/bin/env python #coding:utf-8 import socket,traceback host = ‘‘ port = 51423 s =socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.bind((host,port)) while 1: try: message,addr = s.recvfrom(8192) print "Got data from " ,addr s.sendto("I am here",addr) except (KeyboardInterrupt,SystemExit): raise except: traceback.print_exc(
广播的客户端,客户端特别需要注意的是广播的地址写发,为<broadcaset>.
代码如下:
#!/usr/bin/env python #coding:utf-8 import socket,sys dest = (‘<broadcast>‘, 51423) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.sendto("hello",dest) print "looking for replies: press Ctrl + c to stop " while 1: (buf ,address) = s.recvfrom(2048) if not len(buf): break print "Revived from %s:%s" %(address ,buf)
本文出自 “弹指26年” 博客,请务必保留此出处http://dbbruce.blog.51cto.com/2061658/1568199
标签:udp 广播 python recvfrom sendto
原文地址:http://dbbruce.blog.51cto.com/2061658/1568199