Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: str does not support buffer interface [duplicate]

Tags:

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?

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)
like image 893
Morgan Avatar asked Aug 02 '12 16:08

Morgan


1 Answers

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.

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 strings are quotes enclosed strings. Bytes strings are b"" enclosed strings

See What's new in python 3.0 .

like image 66
Scharron Avatar answered Oct 22 '22 14:10

Scharron