You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UDP Socket编程报错:'bytes' object has no attribute 'recvfrom' 求助

UDP Socket编程错误修复:'bytes' object has no attribute 'recvfrom'

错误核心原因

服务器代码中,s.recvfrom(1024)返回的第一个值是客户端发送的字节数据,而非客户端socket对象(UDP是无连接协议,无需维护客户端socket)。你将该字节数据赋值给变量c后,调用c.recvfrom()自然触发错误——bytes类型没有recvfrom方法。

此外代码还有其他问题:

  • 未将收到的字节数据转换为整数,直接相乘会导致字节拼接而非数值计算。
  • s.sendto()缺少客户端地址参数,无法将结果发回给客户端。

修复后的服务器代码

from socket import socket, AF_INET, SOCK_DGRAM

s = socket(AF_INET, SOCK_DGRAM)
print('Socket created!')

s.bind(('localhost', 11111))

while True:
    # 接收第一个数字并转换为整数
    num1_bytes, addr = s.recvfrom(1024)
    num1 = int(num1_bytes.decode('utf-8'))
    
    # 接收第二个数字并转换为整数
    num2_bytes, addr = s.recvfrom(1024)
    num2 = int(num2_bytes.decode('utf-8'))
    
    print('Received from client having address:', addr)
    product = num1 * num2
    print('The product of the numbers sent by the client is:', product)
    
    # 将乘积编码后发送给客户端,必须指定目标地址
    s.sendto(str(product).encode('utf-8'), addr)

优化后的客户端代码

from socket import socket, AF_INET, SOCK_DGRAM

c = socket(AF_INET, SOCK_DGRAM)

num1 = input('Input a number: ')
num2 = input('Enter a second number: ')

# 发送两个数字到服务器
c.sendto(num1.encode('utf-8'), ('localhost', 11111))
c.sendto(num2.encode('utf-8'), ('localhost', 11111))

# 接收服务器返回的计算结果
product_bytes, addr = c.recvfrom(1024)
print(f"The product is: {product_bytes.decode('utf-8')}")

关键修复说明

  1. 服务器使用自身sockets两次调用recvfrom(),分别获取两个数字的字节数据,避免混淆字节数据与socket对象。
  2. 将解码后的字符串转换为整数,确保数值运算正确。
  3. sendto()添加客户端地址addr,保证结果能准确发回给发起请求的客户端。
  4. 客户端调整接收逻辑,正确解析并打印服务器返回的乘积。

内容的提问来源于stack exchange,提问作者Kryptex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:05:43