using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 发电厂.SocketManagement
{
    internal class Socket_Server
    {
        private TcpListener Server;
        private Thread listenerThread;
        private RichTextBox logTextBox;  // 用于显示日志的控件
        private Socket clientSocket;

        // 构造函数接受日志输出的控件
        public Socket_Server(RichTextBox logBox)
        {
            this.logTextBox = logBox;
        }

        public void StartServer()
        {
            try
            {
                Server = new TcpListener(IPAddress.Parse("127.0.0.1"), 12345);
                Server.Start();
                LogMessage("服务端已启动，等待客户端连接...");

                listenerThread = new Thread(ListenForClients);
                listenerThread.Start();
            }
            catch(Exception ex)
            {
                LogMessage("启动服务端失败: " + ex.Message);
            }
        }

        private void ListenForClients()
        {
            while(true)
            {
                try
                {
                    Socket clientSocket = Server.AcceptSocket();
                    LogMessage("客户端已连接.");

                    // 启动新的线程来处理每个客户端的消息
                    Thread clientThread = new Thread(() => HandleClient(clientSocket));
                    clientThread.Start();
                }
                catch(Exception ex)
                {
                    LogMessage("等待连接失败: " + ex.Message);
                }
            }
        }

        private void HandleClient(Socket clientSocket)
        {
            byte[] buffer = new byte[1024];
            try
            {
                while(true)
                {
                    int num = clientSocket.Receive(buffer);
                    if(num == 0) break;

                    string message = Encoding.UTF8.GetString(buffer, 0, num);
                    LogMessage(message);

                }
            }
            catch(Exception ex)
            {
                LogMessage("处理客户端消息失败: " + ex.Message);
            }
            finally
            {
                clientSocket.Close();
                LogMessage("客户端连接已关闭");
            }
        }

        // 用于更新日志文本框的方法
        public void LogMessage(string message)
        {
            if(logTextBox.InvokeRequired)
            {
                logTextBox.Invoke(new Action<string>(LogMessage), message);
            }
            else
            {
                logTextBox.AppendText(message + Environment.NewLine);
            }
        }

        // 关闭服务端连接
        private void CloseServer()
        {
            if(Server != null)
            {
                Server.Stop();  // 关闭服务端监听套接字
            }
        }

        // 窗口关闭时自动关闭服务端
        private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseServer();  // 关闭服务端连接
        }
    }
}
