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() 获取的字节数据解码为字符串

相关推荐
白帽黑客沐瑶2 天前
【网络安全就业】信息安全专业的就业前景(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·程序员·编程·网络安全就业
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆2 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
树码小子2 天前
Java网络编程:(socket API编程:TCP协议的 socket API -- 回显程序的服务器端程序的编写)
java·网络·tcp/ip
乌萨奇也要立志学C++2 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
绿箭柠檬茶2 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
real 12 天前
传输层协议UDP
网络·网络协议·udp
獭.獭.2 天前
Linux -- 信号【上】
linux·运维·服务器
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
ZERO_pan2 天前
服务器装机遇到的问题
运维·服务器