Python 一个简单udp 的server 与 Client 例子,需要server 先启动,client 后启动.
# -*- coding: cp936 udp Server 先启动 -*- zdt
import socket,time
import random
Lport = 8013
Rport = 8012
host = "localhost"
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#从给定的端口,从任何发送者,接收UDP数据报
s.bind((host,Lport))
print 'bind to the ' ,host ,Lport
while True:
try:
data,addr = s.recvfrom(1024)
#接收一个数据报(最大到1024字节)
print 'received:',data,"from ",addr
s.sendto(data,(host,Rport))
if data=='exit':
break
except:
print "error in client..."
break
s.close
msg = raw_input("Press any key to exit...")
# -*- coding: cp936 udp Client 后启动-*- zdt
import socket,time,random
Lport = 8012
Rport = 8013
host = "localhost"
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,Lport))
print 'bind to the ' ,host ,Lport
i=1
while True:
try:
#msg=raw_input('Type your information\n')
msg='hello'
if (msg=='q' or i>20) :
s.sendto('exit',(host,Rport))
break
else:
s.sendto(str(i)+ ":"+str(random.uniform(1, 100)),(host,Rport))
#time.sleep(1)
data,addr = s.recvfrom(1024)
print i,':received:',data,"from ",addr
i=i+1
except:
print "error at sever, the serer didn't start..."
break
s.close
raw_input('Press any key to exit....')
********************************************************************************
Python 一个简单udp 的server 与 Client 例子,需要server 先启动,client 后启动.