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)
  1. 直接使用 bytes 字面量:
复制代码
python 
send_data = b"hello server"
tcp_socket.send(send_data)
  1. 如果服务端是 Python 2,可使用 str,添加编码声明:
复制代码
python
# -*- coding: utf-8 -*-

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

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

相关推荐
爱学习 爱分享8 小时前
k8s 开启防火墙,容器内部无法访问外部 ip
tcp/ip·容器·kubernetes
发光小北8 小时前
Profinet 从站转 EtherNet/IP 从站网关如何应用?
网络·网络协议·tcp/ip
wangl_928 小时前
Modbus RTU 与 Modbus TCP 深入指南-Wireshark抓包分析实战
网络协议·tcp/ip·wireshark·tcp·modbus·rtu
高锰酸钾_9 小时前
计算机网络-链路层-介质访问控制
网络·计算机网络
源远流长jerry10 小时前
Linux 网络发送机制深度解析:从应用到网线
linux·服务器·网络·网络协议·tcp/ip
goyeer11 小时前
【ITIL4】32服务实践 - 问题管理(Problem Management)
linux·运维·服务器·企业数字化·it管理·itil·it治理
handler0111 小时前
UDP协议与网络通信知识点
c语言·网络·c++·笔记·网络协议·udp
怀旧,11 小时前
【Linux网络编程】8. 网络层协议 IP
linux·网络·tcp/ip
cen__y12 小时前
Linux11(网络编程)
linux·运维·服务器·c语言·网络·网络协议·tcp/ip
CableTech_SQH12 小时前
商业地产和高端酒店该怎么选综合布线解决方案?
运维·服务器·网络