python3使用套接字遇到TypeError: 'str' does not support the buffer interface如何解决
这是我查看的博客
http://blog.csdn.net/chuanchuan608/article/details/17915959
直接引用里面的关键语句:
When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode()
翻译过来,也就是说在你使用python3的时候,如果想要使用套接字组件send发送str类型的东西,记得先encode()一下。同理,当你想用recv接受str东西的时候,记得decode()一下。
为什么会是这样呢?
In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings.
So, now, whenever you have a unicode stringthat you need to use as a byte string, you need toencode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string.
Unicode strings are quotes enclosedstrings. Bytes strings are b"" enclosed strings
原来在python3里面,bytes strings和unicode strings已经是不同的两个类型的(是不是说python2里面是同一类型?不清楚)。由于套接字并不关心字符串的编码方式,他们使用原字节字符串(raw bytes strings)进行传输,而这个类型又和unicode strings又有一点小小的不同。
因此,现在任何时候你要是有一个unicode strings需要把它转化为byte string,你需要对他进行encode操作。当你有bytes string的时候,你需要decode操作。
unicode strings =encode()=》 byte strings
byte strings =decode()=》 unicode strings
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?