#coding:gbk
import socket
import threading
import queue
server=None
def init(ContextInfo):
	print("startint")
	global server
	server = ThreadedServer(port=8886)
	server.start()
	print("started")
def stop(ContextInfo):
    global server
    print('Strategy is stopping!')
    if server is not None:
        server.close_all()
    else:
        print('Server is not running or already stopped.')

class ThreadedServer(threading.Thread):
    def __init__(self, host='0.0.0.0', port=9870):
        super().__init__()
        self.host = host
        self.port = port
        

    def run(self):
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # Allow reuse of local addresses
            self.server_socket.bind((self.host, self.port))
            self.server_socket.listen(1)  # Allow only one client connection at a time
            self.client_handler = None
            print(f"Server initialized on {self.host}:{self.port}. Waiting for connections...")
            while True:
                print("Waiting for a connection...")
                client_socket, client_address = self.server_socket.accept()
                print(f"Connection established with {client_address}.")

                if self.client_handler:
                    self.client_handler.close()

                self.client_handler = ClientHandler(client_socket, client_address)
                self.client_handler.run()
        except KeyboardInterrupt:
            print("\nShutting down server...")
        finally:
            self.close_all()

    def send_msg(self, message):
        if self.client_handler and self.client_handler.running:
            self.client_handler.send_message(message)
        else:
            print("No active client to send message to.")

    def close_all(self):
        if self.client_handler:
            self.client_handler.close()
        self.server_socket.close()
        print("Server socket shut down.")

class ClientHandler:
    def __init__(self, client_socket, client_address):
        self.client_socket = client_socket
        self.client_address = client_address
        self.running = True
        self.send_queue = queue.Queue()
        self.recv_queue = queue.Queue()
        self.buffer = ""

    def run(self):
        threading.Thread(target=self._process_send_queue, daemon=True).start()
        self._receive_messages()

    def send_message(self, message):
        self.send_queue.put(message)
        
    def _process_send_queue(self):
        while self.running:
            try:
                message = self.send_queue.get(timeout=1)
                self.client_socket.sendall(message.encode('utf-8'))
                print(f"Sent to {self.client_address}: {message}")
            except queue.Empty:
                continue
            except Exception as e:
                print(f"Error sending to {self.client_address}: {e}")
                self.running = False

    def _receive_messages(self):
        while self.running:
            try:
                data = self.client_socket.recv(1024)
                if not data:
                    print(f"{self.client_address} disconnected")
                    break

                self.buffer += data.decode('utf-8')
                while '\n' in self.buffer:
                    message, self.buffer = self.buffer.split('\n', 1)
                    print(f"Received from {self.client_address}: {message.strip()}")
                    self.recv_queue.put(message.strip())
            except Exception as e:
                print(f"Error receiving from {self.client_address}: {e}")
                break

        self.close()

    def close(self):
        self.running = False
        if self.client_socket:
            self.client_socket.close()
        print(f"Connection closed with {self.client_address}.")  代码有点问题帮忙优化一下