enter image description here我一直在尝试用python写一个基于服务器-客户端的项目,下面是我的server.py的代码:
#! /usr/bin/env python3
import sys, struct, socket, threading, logging
# create a server socket that connects to 127.0.0.1 on port 512583
HOST = "127.0.0.1"
PORT = 52583
MSGLEN = 2048
def recv_all(conn,n):
chunks = b''
bytes_recd = 0
while bytes_recd < n:
chunk = conn.recv(min(n - bytes_recd, 1024))
#if len(chunk) == 0:
# raise RuntimeError("socket connection broken")
chunks += chunk
bytes_recd = bytes_recd + len(chunk)
return chunks
def handle_client(conn, addr):
print(f"Contacted by {addr}")
with conn:
while True:
data = recv_all(conn, 4)
print("test")
print(f"Length",len(data))
input = struct.unpack("!i", data)[0]
print(f"Received", input)
if not data:
break
conn.sendall(struct.pack("!i",input))
print(f"Sent", input)
def main(host=HOST, port=PORT):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((host, port))
s.listen()
print(f"Server listening on {host}:{port}")
#logging.basicConfig(filename= 'server.log' , level=logging.INFO, format='%(asctime)s - %(message)s')
while True:
print("Waiting for a connection...")
conn, addr = s.accept()
client_thread = threading.Thread(target=handle_client, args=(conn, addr))
client_thread.start()
except KeyboardInterrupt:
pass
print("Server shutting down")
s.shutdown(socket.SHUT_RDWR)
sys.exit(1)
if __name__ == "__main__":
main()
字符串
不幸的是,当我试图关闭它从终端“服务器关闭”出现,但它并没有真正关闭。有人能帮帮我吗多谢了
如果我再次按下Ctrl+C,它会显示:
1条答案
按热度按时间wh6knrhe1#
你的
handle_client
函数阻塞了(有一个永远不会结束的while
循环)。sys.exit
正在等待线程结束。你需要自己结束线程。我认为大多数服务器都是在所有客户端断开连接时关闭的。因此,当客户端断开连接时,您将关闭
handle_client
线程。(或者你可以在Ctrl-C上杀死它,但这可能是个坏主意(阅读:腐败))