白云岛资源网 Design By www.pvray.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"
 
白云岛资源网 Design By www.pvray.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
白云岛资源网 Design By www.pvray.com