python使用socket模块基于udp协议进行互相发送

2025-12-20T11:39:00

python使用socket模块基于udp协议进行互相发送

  • tcp与udp最大区别时不需要建立连接,所以稳定性无法保证

服务端

  • 使用sendto发送消息,格式为server_obj.sendto(data,(ip,port))
  • 使用recvfrom接收消息,格式为data,(ip,port) = client_obj.recvfrom(2048)

    • 接收对象返回值为 数据,ip和port
#使用udp协议接收信息
import socket

#对象实例化
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('127.0.0.1', 9999))

#接收消息
while True:
    data,(ip,port) = server.recvfrom(1024)
    print(f'{ip}:{port},发送的消息为{data.decode()}')

    #回复收到
    server.sendto('收到了'.encode(),(ip,port))



客户端

#使用udp发送信息
import socket

#对象实例化
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


#发送消息
while True:
    user_input = input("Enter a number: ")
    if user_input.upper() == "Q":
        break

    client.sendto(user_input.encode(), ("127.0.0.1", 9999))

    #检查服务端是否收到
    client_data, (ip,port) = client.recvfrom(2048)
    print(f'服务端{ip}:{port}: {client_data.decode()}')

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »