using System;
using System.Text;
using System.Threading;
using TouchSocket.Core.Config;
using TouchSocket.Core.Plugins;
using TouchSocket.Sockets;

namespace Tcp.Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var encoding = Encoding.GetEncoding("gb2312");
            var tcpClient = new TcpClient();
            tcpClient.Connected += (client, e) => { Console.WriteLine("成功连接服务器"); };//成功连接到服务器
            tcpClient.Disconnected += (client, e) => { Console.WriteLine("与服务器断开连接"); };//从服务器断开连接，当连接不成功时不会触发。
            tcpClient.Received += (client, byteBlock, requestInfo) =>
            {
                //从服务器收到信息
                string mes = encoding.GetString(byteBlock.Buffer, 0, byteBlock.Len);
                Console.WriteLine($"接收到信息：{mes}");
            };

            //声明配置
            var config = new TouchSocketConfig();
            config.SetRemoteIPHost(new IPHost("127.0.0.1:8308"))
                .UsePlugin()
                .ConfigurePlugins(a =>
                {
                    a.UseReconnection(5, true, 1000);
                })
                .SetBufferLength(1024 * 10);

            //载入配置
            tcpClient.Setup(config);
            Connection:
            ConnectServer(tcpClient);
            try
            {
                while (true)
                {
                    var res = Console.ReadLine();
                    if (!string.IsNullOrWhiteSpace(res))
                    {
                        var bytes = encoding.GetBytes(res);
                        tcpClient.Send(bytes);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生异常：" + ex.Message);
                goto Connection;
            }
        }
        private static void ConnectServer(TcpClient client) 
        {
            while (true) 
            {
                Console.WriteLine("正在连接服务器...");
                try
                {
                    client.Connect();
                    Console.WriteLine("连接成功");
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("连接失败：" + ex.Message);
                    Thread.Sleep(1000);
                }
            }
        }
    }
}
