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

Python3中如何创建byte类型对象?Socket客户端发送数据报错求助

解决Python3 Socket发送数据的字节类型错误问题

你遇到的问题是Python3 Socket API的典型特性——send()方法要求必须传入bytes类型的数据,而你客户端代码里传的是普通字符串'Test',这就是报错的核心原因。

解决这个问题非常简单,有两种常用的方式把字符串转换成bytes:

  • 直接在字符串前加b前缀,创建字节字面量:b'Test'
  • 调用字符串的encode()方法,指定编码格式(推荐使用utf-8):'Test'.encode('utf-8')

下面是修改后的客户端代码,我仅调整了发送数据的那一行:

import socket
s = socket.socket()
host = socket.gethostname()
port = 60000

s.connect((host, port))
# 将字符串转为bytes类型后发送
s.send(b'Test')  # 也可以用 s.send('Test'.encode('utf-8'))

with open('received_file', 'wb') as f:
    print ('file opened')
    while True:
        print('receiving data...')
        data = s.recv(1024)
        print('data=%s', (data))
        if not data:
            break
        # 写入文件(bytes类型直接写入二进制文件)
        f.write(data)

f.close()
print('Successfully get the file')
s.close()
print('connection closed')

额外补充:服务端通过recv()接收到的是bytes类型数据,如果之后需要转成字符串处理,可以用data.decode('utf-8')完成反向转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:34