类型错误:str 不支持缓冲区接口 [英] TypeError: str does not support buffer interface

查看:64
本文介绍了类型错误:str 不支持缓冲区接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的客户端 &python中的服务器消息传递程序,我不断收到错误TypeError:'str'不支持缓冲区接口",甚至不知道这意味着什么.我大部分时间都是 Python 初学者,也是网络初学者.

I'm trying to make a simple client & server messaging program in python, and I keep getting the error "TypeError: 'str' does not support the buffer interface" and don't really even know what that means. I'm a beginner with python for the most part, and a complete begginer with networking.

我假设出于某种原因无法发送字符串数据?如果是这种情况,我将如何发送字符串?

I'm assuming for some reason I can't send string data? If this is the case, how would I send a string?

作为参考,我从中获得的大部分示例代码是针对 python 2.x 的,而我正在 Python 3 中执行此操作,因此我相信这是从版本转换中解决的另一个问题.我已经四处寻找相同的问题,但无法真正弄清楚如何将相同的修复程序应用于我的情况.

For reference, the example code I got most of this from was for python 2.x, and I'm doing this in Python 3, so I believe it's another kink to work out from version transition. I've searched around for the same problem, but can't really work out how to apply the same fixes to my situation.

这是服务器的开始代码:

Here's the beginning code for the server:

import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 5000))
server_socket.listen(5)

print("TCP Server Waiting for client on port 5000")

while 1:
    client_socket, address = server_socket.accept()
    print("TCP Server received connect from: " + str(address))
    while 1:
        data = input("SEND(Type q or Q to quit):")
        if(data == 'Q' or data == 'q'):
            client_socket.send(data)
            client_socket.close()
            break;
        else:
            client_socket.send(data)
            data = client_socket.recv(512)

        if(data == 'q' or data == 'Q'):
            client_socket.close()
            break;
        else:
            print("Received: " + data)

推荐答案

在 python 3 中,字节字符串和 unicode 字符串现在是两种不同的类型.由于套接字不知道字符串编码,因此它们使用原始字节字符串,其接口与 unicode 字符串略有不同.

In python 3, bytes strings and unicode strings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly different interface from unicode strings.

所以,现在,每当您有一个需要用作字节字符串的 unicode 字符串时,您都需要 encode() 它.当你有一个字节串时,你需要 decode 它以将它用作常规(python 2.x)字符串.

So, now, whenever you have a unicode string that you need to use as a byte string, you need to encode() it. And when you have a byte string, you need to decode it to use it as a regular (python 2.x) string.

Unicode 字符串是用引号括起来的字符串.字节字符串是 b"" 封闭的字符串

Unicode strings are quotes enclosed strings. Bytes strings are b"" enclosed strings

python 3.0 中的新功能 .

这篇关于类型错误:str 不支持缓冲区接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆