coding = 'utf-8'
link = ('127.0.0.1', 8000)
BUFFER_SIZE = 1024
# UDP 协议 基于数据报的协议,没有管道或建立连接的情况,不会粘包,多余数据不会留在缓存
# 服务端
from socket import *
server = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM 数据报协议,代表UDP, 允许发空(实际上有地址)
server.bind(*link)
# server.listen(5)
# while 1:
# conn, addr = server.accept() # 无握手,不等待
while 1:
msg, client_addr = server.recvfrom(BUFFER_SIZE )
print(msg)
server.sendto(msg.upper(), client_addr)
if msg == 'end':
server.close()
break
# 客户端
from socket import *
client = socket(AF_INET, SOCK_DGRAM)
while 1:
msg = input('>>').strip()
client.sendto(msg.encode(coding), link)
data, server_addr = client.recvfrom(BUFFER_SIZE)
print(data, server_addr)
if msg == 'end':
client.close()
break