# ### udp 协议 服务端 import socket # socket.SOCK_DGRAM 代表udp协议 sk = socket.socket(type = socket.SOCK_DGRAM) # 绑定地址 sk.bind( ("127.0.0.1",9000) ) # udp作为服务器,第一次一定是先接受消息 msg,cli_addr = sk.recvfrom(1024) print(msg,cli_addr) msg2 = "对,确实不错,因为今天周五" # sendto ( "要发送的消息".encode() , (ip,端口) ) sk.sendto(msg2.encode("utf-8"),cli_addr) # 关闭udp连接 sk.close()
# ### udp 客户端 import socket sk = socket.socket(type=socket.SOCK_DGRAM) msg = "今天天气不错" # udp 发送数据 # sendto ( "要发送的消息".encode() , (ip,端口) ) sk.sendto(msg.encode("utf-8"),("127.0.0.1",9000)) # udp 接受数据 msg,addr = sk.recvfrom(1024) print(msg,addr) res = msg.decode("utf-8") print(res) # 关闭udp连接 sk.close()