一个非常基本的问题,但是我找不到我的错误。我基本上使用this教程代码来实现自己的客户端-服务器程序:客户端发送一些数据,服务器将其显示(而不是像教程中那样回显数据)
回显的教程代码有效,但是我调整后的代码无法在服务器上打印数据。我添加了一些定界符机制来检测整个消息。我的代码:
Server.py:
class ThreadedServer:
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))
print("Server bound on Port "+str(port))
def listen(self):
self.sock.listen(5)
while True:
print("Waiting for incoming connections...")
client, address = self.sock.accept()
client.settimeout(60)
print("Starting Working thread.")
threading.Thread(target=self.listenToClientDelimiter, args=(client, address)).start()
def listenToClientDelimiter(self, client, address):
print("Connect to client "+address)
length = None
buffer = ""
while True:
data = client.recv(1024)
print("Received raw data: "+str(data))
if not data:
break # connection closed
buffer += data
while True:
if length is None:
if LENGTH_DELIMITER not in buffer:
break # delimiter not found, wait for next data package
length_str, _, buffer = buffer.partition(LENGTH_DELIMITER)
length = int(length_str)
if len(buffer) < length:
break # wait until full length got received before we proceed
message = buffer[:length]
buffer = buffer[length:]
length = None
# PROCESS MESSAGE HERE
print(message)
client.close()
if __name__ == "__main__":
ThreadedServer('', 65432).listen()
Client.py:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("127.0.0.1", 65432))
connect_user_cmd = "18:CONNECT_USER;Peter"
print("Trying to send data: "+connect_user_cmd.decode())
print(s.send(connect_user_cmd))
我先运行服务器,然后运行客户端。服务器的输出:
Server bound on Port 65432
Waiting for incoming connections...
如您所见,我希望收到一些日志消息,当然还有我发送的消息。客户端输出以下内容:
Trying to send data: 18:CONNECT_USER;Peter
21
Process finished with exit code 0
即使我不启动服务器,它也会从客户端输出。奇怪的是,回声部分确实起作用了。有人可以提示我正确的方向吗?谢谢!