欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现的udp协议Server和Client代码实例

程序员文章站 2023-11-20 13:17:40
直接上代码:server端:复制代码 代码如下: #!/usr/bin/env python # udp echo server -  udp...
直接上代码:
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"