17
votes

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)
1
Try sending StringIO.StringIO(data) instead of just data. - Andrew Clark
As a side note: you can simplify your if-statements as follows if data in ('q', 'Q'): - gsk
@gsk: Or if data.lower() == "q":. - Tim Pietzcker
@gsk: No, that would also return True for data = "" or data = "qQ". - Tim Pietzcker
@Morgan Yes, why? I flagged it because when people are searching for a solution to your problem, it might also help to see the other post's answers. I think also that duplicate questions should be merged. - nbro

1 Answers

54
votes

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 .