好的,我正在用python3创建一个客户端和服务器,但是每当我尝试比较从客户端接收到的内容时,它都无法正常工作,并返回错误,如最后所示。这是我的服务器的代码(使用线程):
import socket
import threading
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(600)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
data = client.recv(size)
data = data.decode("utf-8")
# Reply
if data == "lad":
response = "nice"
else:
response = data
client.send(response)
if __name__ == "__main__":
while True:
host = input("Host? ")
port_num = input("Port? ")
try:
port_num = int(port_num)
print("Please connect client")
break
except ValueError:
pass
ThreadedServer(host,port_num).listen()
ThreadedServer(host,port_num).listen()
ThreadedServer.listenToClient()
“数据”是我从客户端收到的。
错误是这样的:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python34\lib\threading.py", line 911, in _bootstrap_inner
self.run()
File "C:\Python34\lib\threading.py", line 859, in run
self._target(*self._args, **self._kwargs)
File "H:\KS4\IT\Computer science\Python\Socketing\AutoServer.py", line 33, in listenToClient
client.send(response)
TypeError: 'str' does not support the buffer interface