python创建udp服务端和客户端
Posted 卖鱼熊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python创建udp服务端和客户端相关的知识,希望对你有一定的参考价值。
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()
以上是关于python创建udp服务端和客户端的主要内容,如果未能解决你的问题,请参考以下文章