python的udp广播服务器和客户端例子
今晚因为工作的关系想了解一下网络广播,但是找了很久没有在中文网站上找到一套可用的例子,于是决定自己用python写一个,还好在e文网站上找到一个广播服务器的例子,自己写了客户端的,就是下面两个小程序了.
#!/usr/bin/env python
# this is the udp broadcast server
import socket, traceback
host = '' # Bind to all interfaces
port = 1234
print "python UDP multi case server test"
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))
for i in range(1,100):
try:
s.sendto("server here",('192.168.1.255', 2345))
message, address = s.recvfrom(1234)
print "Got data from", address,":",message
# Acknowledge it.
s.sendto("I am here", address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
#!/usr/bin/env python
#this is the udp broadcast client
import socket, traceback
port = 2345
print "python UDP multi case client test"
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)
data = "Data from pc"
s.bind(("",2345))
for i in range(1,100):
try:
data,address=s.recvfrom(2345)
print "cli get data form", address, ":", data
s.sendto("client ack", address)
#data,address = s.recvfrom(1024)
#print "received %r from %r" % (data, address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
print "test finsh"