005---基于UDP的套接字
基于UDP的套接字
udp不同于tcp协议:不需要经过三次握手、四次挥手。直接发送数据就行。
服务端
import socket
ip_port = ('127.0.0.1', 8001)
buffer_size = 1024
service = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# 绑定
service.bind(ip_port)
print('start...')
while 1:
data, addr = service.recvfrom(buffer_size)
print('客户端发来的数据:', data.decode('utf-8'))
print('客户端的信息:', addr)
msg = input('给%s发送的消息:' % addr[1]).strip()
service.sendto(msg.encode('utf-8'), addr)
print('给客户端%s的消息:%s 发送成功' % (addr[1], msg))
客户端
import socket
ip_port = ('127.0.0.1', 8001)
buffer_size = 1024
client = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
while 1:
msg = input('给服务器发送消息:').strip()
if not msg:
continue
client.sendto(msg.encode('utf-8'), ip_port)
data, addr = client.recvfrom(buffer_size)
print(addr)
print('服务器发来的消息:%s' % data.decode('utf-8'))