Python 使用多线程从TCP服务器中的线程返回值
我有一个python小型服务器,其中包含一个计时器(代码中的计时器类)。Python 使用多线程从TCP服务器中的线程返回值,python,multithreading,sockets,tcp,Python,Multithreading,Sockets,Tcp,我有一个python小型服务器,其中包含一个计时器(代码中的计时器类)。 计时器在线程中运行,每次我通过客户端指示服务器启动时钟(客户端中的命令clk),它都应该开始计数。每秒应在服务器中返回经过的时间,并在客户端返回一条消息TicTac 但是,我无法将消息发送回客户端,直到我停止时钟(客户端中的命令clk_stop)。 我怎样才能解决这个问题 服务器: import threading from datetime import datetime import time from queue i
计时器在线程中运行,每次我通过客户端指示服务器启动时钟(客户端中的命令clk),它都应该开始计数。每秒应在服务器中返回经过的时间,并在客户端返回一条消息TicTac 但是,我无法将消息发送回客户端,直到我停止时钟(客户端中的命令clk_stop)。 我怎样才能解决这个问题 服务器:
import threading
from datetime import datetime
import time
from queue import Queue
import server
# global variables
HEADER = 64
PORT = 5050
SERVER = "127.0.0.1" #socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "exit"
CONFIRM_MESSAGE = ("Message Received.").encode(FORMAT)
class Timer(object):
def __init__(self):
self._running = True
def terminate(self):
self._running = False
delta_time = datetime.now() - self.start_time
print("Chronometer Stop Time: ", delta_time)
def run(self, conn, q):
self.start_time = datetime.now()
while self._running:
time.sleep(1)
if self._running:
delta_time = datetime.now() - self.start_time
q.put(str(delta_time))
print("Chronometer: ", delta_time)
class MessageHandler(object):
def read_message(self, conn, addr, msg, q):
print(f"Address {addr}: Message: {msg}")
if (msg == "start"):
conn.send(("[STARTING TIMER]").encode(FORMAT))
self.timer = Timer()
self.thread = threading.Thread(target=self.timer.run, args=(conn, q)) #, daemon = True
self.thread.start()
elif(msg == "stop"):
self.timer.terminate()
return CONFIRM_MESSAGE
else:
return CONFIRM_MESSAGE
def handle_client(conn, addr, q):
print(f"\n[NEW CONNECTION] {addr} connected.")
mh = MessageHandler()
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
return_msg = mh.read_message(conn, addr, msg, q)
if(return_msg != None):
conn.send(return_msg)
conn.close()
if __name__ == "__main__":
server = socket.socket(family = socket.AF_INET, type = socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(ADDR)
print("[STARTING] server is starting...")
server.listen() # We can use an argument that is an int and limitates the number of connections
print(f"[LISTNING] Server is listening on {SERVER}")
while True:
queue1 = Queue()
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr, queue1))
thread.start()
while not queue1.empty():
result = queue1.get()
print(result)
queue1.send(result)