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

相关推荐
网易独家音乐人Mike Zhou24 分钟前
【Linux应用】开发板USB共享网络,网线或USB以太网共享网络(局域网连接PC和开发板,实现PC给开发板共享网络,USB通过NDIS驱动共享)
linux·网络·单片机·mcu·物联网·嵌入式·iot
托比-马奎尔42 分钟前
第十二章:网络编程
网络
颖川初尘1 小时前
端口到底是个什么鬼?回答我!
服务器·网络·tcp/ip·node.js
stark张宇2 小时前
Linux 文件创建、删除、移动、复制基础知识整理
linux·服务器·centos
将心ONE2 小时前
使用 lstrip() 和 rstrip() 方法
运维·服务器
daikaimiao3 小时前
https——TCP+TLS
网络协议·tcp/ip·https
Two_brushes.4 小时前
【linux网络】深入理解 TCP/UDP:从基础端口号到可靠传输机制全解析
linux·运维·服务器
FJW0208144 小时前
【Linux】系统引导修复
linux·运维·服务器
nightunderblackcat4 小时前
新手向:Python网络编程,搭建简易HTTP服务器
网络·python·http
设计师小聂!4 小时前
linux常用命令(一)
linux·运维·服务器