You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 from recv() 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 the send() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:23:50