using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace 试验版
{
    internal class socket_client
    {


        
        private Socket Client;
        private RichTextBox logTextBox;  // 用于显示日志的控件
        private string name;
        // 构造函数接受日志输出的控件
        public socket_client(RichTextBox logBox)
        {
            this.logTextBox = logBox;
        }

        public void StartClient()
        {
            try
            {
                Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Client.Connect("127.0.0.1", 12345);
                LogMessage("已连接，注册名字");

                name = "废物七号";  // 可以替换为用户输入
                Client.Send(Encoding.UTF8.GetBytes(name + $"({Client.RemoteEndPoint})已连接"));

                // 启动接收消息线程
                Thread th = new Thread(ReceiveMsg);
                th.Start();

            }
            catch (Exception ex)
            {
                LogMessage("连接失败: " + ex.Message);
            }
        }

        private void ReceiveMsg()
        {
            byte[] buffer = new byte[1024];
            try
            {
                while (true)
                {
                    int num = Client.Receive(buffer);
                    if (num == 0) break;  // 服务端关闭
                    string message = Encoding.UTF8.GetString(buffer, 0, num);
                    LogMessage(message);
                }
            }
            catch (Exception ex)
            {
                LogMessage("接收失败: " + ex.Message);
            }
            finally
            {
                Client.Close();
                LogMessage("连接已关闭");
            }
        }

        public void SendMessage(string message)
        {
            LogMessage(message);
            if (Client != null && Client.Connected)
            {
                byte[] messageBytes = Encoding.UTF8.GetBytes(name + "：" + message);
                Client.Send(messageBytes);  // 向服务端发送消息
            }
        }

        private void ReceiveMessages()
        {
            byte[] buffer = new byte[1024];
            while (true)
            {
                int received = Client.Receive(buffer);
                if (received > 0)
                {
                    string receivedMessage = Encoding.UTF8.GetString(buffer, 0, received);
                    LogMessage("服务端接收: " + receivedMessage);
                }
            }
        }

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

        // 关闭客户端连接
        private void CloseClient()
        {
            if (Client != null && Client.Connected)
            {
                Client.Shutdown(SocketShutdown.Both);  // 关闭发送和接收
                Client.Close();  // 关闭连接
            }
        }

        // 窗口关闭时自动关闭客户端
        private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseClient();  // 关闭客户端连接
        }
        
        

    }
}
