服务器端:
import socket
sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8888)
sk.bind(ip_port)
while True:
print("等待输入....")
data = sk.recv(1024)
print(data.decode())
客户端:
import socket
#定义实例
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8888)
while True:
msg_input = input('请输入要发送的信息: ')
#定义退出的条件
if msg_input == "exit":
break
sk.sendto(msg_input.encode(), ip_port)
#发送关闭信息给服务器,虽然会自动关闭,但为了资源节省,还是主动关闭.
sk.close()