TypeError: a bytes-like object is required, not ‘str‘

raceback (most recent call last):
  File "D:\pycharmcode\client.py", line 12, in <module>
    tcp_socket.send(send_data)
TypeError: a bytes-like object is required, not 'str'

使用socket进行ubuntu与windows通信时,发送数据时报了以上错误

解决办法是:

这个错误表示在使用 TCP socket 的 send() 方法发送数据时,传入的参数类型错误,需要 bytes-like 对象,而传入的是 str。在 Python 3 中,socket 模块的 send() 和 recv() 方法需要传入和返回 bytes 对象,不能直接处理字符串。解决方法是:1. 使用 str.encode() 方法对字符串进行编码:

python
send_data = "hello server".encode("utf-8")
tcp_socket.send(send_data)

2. 直接使用 bytes 字面量:

python 
send_data = b"hello server"
tcp_socket.send(send_data)

3. 如果服务端是 Python 2,可使用 str,添加编码声明:

python
# -*- coding: utf-8 -*-

send_data = "hello server"
tcp_socket.send(send_data)

所以正确的做法是调用 encode() 或者直接使用 bytes 对象,将需要发送的数据统一转换为字节后再发出。同理,在接收数据时需要对 recv() 获取的字节数据解码为字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值