---------------------------------------udp_server.py---------------------------------------
# coding:utf-8
import socket
udp_server = socket.socket(type=socket.SOCK_DGRAM) # 创建socket对象,DGRAM:datagram 数据报文,UDP协议通信
ip_port = ("127.0.0.1", 8001)
udp_server.bind(ip_port) # 绑定IP和端口号
from_client_msg, client_addr = udp_server.recvfrom(1024) # 接收来自客户端的消息
print("来自客户端的消息:", from_client_msg.decode("utf-8"))
server_input = input(">>>: ").strip()
udp_server.sendto(server_input.encode("utf-8"), client_addr) # 给客户端发送消息
udp_server.close() # 关闭连接
---------------------------------------udp_client.py---------------------------------------
# coding:utf-8
import socket
udp_client = socket.socket(type=socket.SOCK_DGRAM) # 创建socket对象,DGRAM:datagram 数据报文,UDP协议通信
ip_port = ("127.0.0.1", 8001)
client_input = input(">>>: ").strip()
udp_client.sendto(client_input.encode("utf-8"), ip_port) # 给服务端发送消息
from_server_msg, server_addr = udp_client.recvfrom(1024) # 接收来自服务端的消息,最大为1024B
print("来自服务端的消息:", from_server_msg.decode("utf-8"))
udp_client.close() # 关闭连接
UDP练习的需求是这样的:
1、服务端需要提供的服务有:接收消息(时间格式的字符串)、将我的本地的时间转换成接收到的消息的格式(也就是个时间格式的字符串)、发回给客户端。
2、客户端自行想一下怎么写。
---------------------------------------practice_udp_server.py---------------------------------------
# coding:utf-8
import socket
import time
udp_server = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ("127.0.0.1", 8001)
udp_server.bind(ip_port)
from_client_msg, addr = udp_server.recvfrom(1024)
print("来自客户端的消息:", from_client_msg.decode("utf-8"))
udp_server.sendto(time.strftime("%Y-%m-%d %X").encode("utf-8"), addr)
udp_server.close()
---------------------------------------practice_udp_client.py---------------------------------------
# coding:utf-8
import socket
udp_client = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ("127.0.0.1", 8001)
client_input = input("格式化时间: ").strip()
udp_client.sendto(client_input.encode("utf-8"), ip_port)
from_server_msg, addr = udp_client.recvfrom(1024)
print("来自服务端的消息:", from_server_msg.decode("utf-8"))
udp_client.close()