圆月山庄资源网 Design By www.vgjia.com
直接上代码:
Server端:
复制代码 代码如下:
 #!/usr/bin/env python
 # UDP Echo Server -  udpserver.py
 import socket, traceback

 host = ''
 port = 54321

 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 s.bind((host, port))

 while 1:
     try:
         message, address = s.recvfrom(8192)
         print "Got data from", address, ": ", message
         s.sendto(message, address)
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         traceback.print_exc()
 
Client端:
复制代码 代码如下: 1 #!/usr/bin/env python
 # UDP Client - udpclient.py
 import socket, sys

 host = sys.argv[1]
 textport = sys.argv[2]

 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 try:
     port = int(textport)
 except ValueError:
     port = socket.getservbyname(textport, 'udp')
 s.connect((host, port))
 while 1:
     print "Enter data to transmit:"
     data = sys.stdin.readline().strip()
     s.sendall(data)
     print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
     buf = s.recv(2048)
     if not len(buf):
         break
     print "Server replies: ",
     sys.stdout.write(buf)
     print "\n"
 
标签:
python,udp协议,Server,Client

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com