面向无连接UDP连接是一种比较方便的连接方式,它不需要和服务器连接,直接将地址和数据封装到一起然后发送,中间如果客户机断开连接,数据也会通过IP地址发送过去。如果IP地址不存在,数据就会消失在网络中。
服务器代码如下:
import socket
HOST = ''
PORT = 8080
ADDRESS = (HOST,PORT)
BUFFER = 1024
client_set = set()
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp_socket.bind(ADDRESS)
print("udp server is starting, waiting for data....")
while True:
msg, addr = udp_socket.recvfrom(BUFFER)
client_set.add(addr)
print(addr,"client:",msg.decode('gbk'))
for client in client_set:
if client != addr:
udp_socket.sendto(msg, client)
客户端代码:
import socket
HOST = '192.168.13.21'
PORT = 8080
ADDRESS = (HOST, PORT)
BUFFER = 1024
a = 0
udp_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
info = input("请输入您的昵称:")
udp_client.sendto(info.encode('gbk'),ADDRESS)
while True:
for i in range(1,a+1):
msg, addr = udp_client.recvfrom(BUFFER)
print(addr,"say:",msg.decode('gbk'))
while True:
a += 1
info = input("请输入您要发送的信息:")
udp_client.sendto(info.encode('gbk'),ADDRESS)
if info == "BYE":
break
网友评论