170925_2 Python socket 创建UDP的服务器端和客户端

【python版本】3.6

UDP服务器端:

 from socket import *
from time import ctime host = ''
port = 21567
buf_size = 1024
addr = (host, port) udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(addr) while True:
print("waiting for message...")
data, ADDR = udpSerSock.recvfrom(buf_size)
response = '[%s] %s' % (ctime(), data.decode('utf-8'))
udpSerSock.sendto(response.encode('utf-8'), ADDR)
print("...received from and returned to:", ADDR) udpSerSock.close()

UDP客户端:

 from socket import *

 host = 'localhost'
port = 21567
buf_size = 1024
addr = (host, port) udpCliSock = socket(AF_INET, SOCK_DGRAM) while True:
data = input('>')
if not data:
break
udpCliSock.sendto(data.encode('utf-8'), addr)
data, addr = udpCliSock.recvfrom(buf_size)
if not data:
break
print(data.decode('utf-8')) udpCliSock.close()
上一篇:ReactiveCocoa基础


下一篇:jupyter nb + scite 混合搭建成我的最爱IDE