服务端:
import socket
# TCP: 9999
# UDP:9999
HOST = '172.25.254.41'
PORT = 9999
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# 绑定端口:
server.bind((HOST, PORT))
# 不需要调用监听方法
print('等待客户端的UDP请求.....')
while True:
# 接收客户端的数据
data, addr = server.recvfrom(1024)
print("接收到客户端的信息:", data)
print("客户端的socket地址为:", addr)
recv_data = input("server>>").encode()
server.sendto(recv_data, addr)
客户端:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ('172.25.254.41', 9999)
while True:
msg = input('client>>')
msg = msg.encode()
client.sendto(msg, address)
print("接收到服务端的消息:", client.recv(1024))
服务端:
等待客户端的UDP请求…..
接收到客户端的信息: b’hello’
客户端的socket地址为: (‘172.25.254.41’, 37766)
server>>ooo
客户端:
client>>hello
接收到服务端的消息: b’ooo’
出现过的错误:OSError: [Errno 99] Cannot assign requested address
和实验室别的ip冲突了