python创建udp服务端和客户端

2018-08-26 17:33:11来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1.udp服务端server

 1 from socket import *
 2 from time import ctime
 3 
 4 HOST = ''
 5 PORT = 8888
 6 BUFSIZ = 1024
 7 ADDR = (HOST, PORT)
 8 
 9 udpSerSock = socket(AF_INET, SOCK_DGRAM)
10 udpSerSock.bind(ADDR)
11 
12 while True:
13     print('waiting for message...')
14     data, addr = udpSerSock.recvfrom(BUFSIZ)
15 
16     content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
17     udpSerSock.sendto(content.encode("utf-8"), addr)
18     print('...received from and returned to:', addr)
19 
20 udpSerSock.close()

 

 

 

2.udp客户端client

 1 from socket import *
 2 
 3 HOST = 'localhost'
 4 PORT = 8888
 5 BUFSIZ = 1024
 6 ADDR = (HOST, PORT)
 7 
 8 udpCliSock = socket(AF_INET, SOCK_DGRAM)
 9 
10 while True:
11     data = input('> ')
12     if not data:
13         break
14 
15     udpCliSock.sendto(data.encode("utf-8"), ADDR)
16     data, ADDR = udpCliSock.recvfrom(BUFSIZ)
17     if not data:
18         break
19     print(data)
20 
21 udpCliSock.close()

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python创建tcp服务端和客户端

下一篇:python 2018/8/25