Python Socket编程报错must be str, not bytes的问题咨询
Hey there! Let's fix that "must be str, not bytes" error in your socket code right away. The core issue here is how Python 3 handles socket communication—all send and receive operations work with byte objects, not plain strings. Let's walk through the fixes for both your server and client code.
Why This Error Happens
In Python 3, unlike Python 2, sockets don't automatically convert between strings and bytes. When you try to send a raw string or concatenate received bytes with a string, Python throws that type mismatch error because it expects bytes for socket operations.
Fixed Server Code
import socket server_socket = socket.socket() server_socket.bind(('0.0.0.0', 8820)) server_socket.listen(1) (client_socket, client_address) = server_socket.accept() # Decode the received bytes to a string client_name = client_socket.recv(1024).decode('utf-8') # Encode the response string to bytes before sending client_socket.send(('Hello ' + client_name).encode('utf-8')) client_socket.close() server_socket.close()
Key changes here:
- Added
.decode('utf-8')to convert the bytes received fromrecv()into a usable string - Used
.encode('utf-8')on the concatenated response string to turn it into bytes before sending it back
Fixed Client Code
import socket my_socket = socket.socket() my_socket.connect(('127.0.0.1', 8820)) # Encode the string to bytes before sending my_socket.send('Sami'.encode('utf-8')) # Decode received bytes to a string for printing data = my_socket.recv(1024).decode('utf-8') print('The server sent:', data) my_socket.close()
Key changes here:
- Added
.encode('utf-8')to convert your "Sami" string into bytes for thesend()call - Decoded the received bytes to a string so you can print it without errors (I also fixed your incomplete print statement!)
Quick Note
We're using UTF-8 as the encoding standard here—make sure both the server and client use the same encoding to avoid garbled text if you ever send non-ASCII characters.
内容的提问来源于stack exchange,提问作者AmitaiF

