TcpClient和TcpListener断开自动重连

在使用QQ的时候,有时候因为网络原因断网使QQ断线,这时候QQ客户端发现与腾讯代理ServerTCP链接中断,而做出每隔多久进行自动重连的行为。

服务端使用TcpListener监听来自客户端的链接:

 class Program
    {
        
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("10.0.0.217");
            TcpListener server = new TcpListener(ip, 40000);
            server.Start();

            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    string id = Guid.NewGuid().ToString();

                    // 异步接受传入的连接尝试,并创建新的 System.Net.Sockets.Socket 来处理远程主机通信。
                    AsyncCallback asynccallback = new AsyncCallback(GetShow);
                    IAsyncResult result = server.BeginAcceptSocket(asynccallback, id);
                    Socket socket = server.EndAcceptSocket(result);
                    result.AsyncWaitHandle.Close();

                    //发送消息
                    socket.Send(Encoding.UTF8.GetBytes(id)); 

                    //接收该Socket发来的数据
                    Thread read_data = new Thread((obj) =>
                    {
                        Socket _s = obj as Socket;
                        if (_s != null)
                        {
                            byte[] bytes = new byte[1024];
                            int i;
                            try
                            {
                                do
                                {
                                    i = _s.Receive(bytes);
                                    if (i > 0)
                                        Console.WriteLine(id + ">>> " + Encoding.UTF8.GetString(bytes, 0, i));
                                } while (i > 0);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("退出:【"+id+"】");
                                _s.Close();
                            }
                        }
                    });
                    read_data.Start(socket);
                }
            });
            thread.Start();
            Console.WriteLine("----------------------------------------------");
            Console.WriteLine("服务端开启服务");
            Console.WriteLine("----------------------------------------------");
            Console.WriteLine();
            Console.Read();
        }


        static void GetShow(IAsyncResult resulr)
        {
            string id = resulr.AsyncState as string;
            Console.WriteLine("进入:【" + id+"】");
        }
    }
客户端使用TcpListener发起链接

    class Program
    {
        static TcpClient tcp_pc = new TcpClient();
        static bool IslinkError = true;

        static void Main(string[] args)
        {
            StaticLink();
            Thread thread = new Thread(() => {
                while (true)
                {
                    if (IslinkError)
                    {
                        tcp_pc = null;
                        tcp_pc = new TcpClient();
                        Console.WriteLine("======================");
                        Console.WriteLine("3秒钟后重新链接服务器");
                        Thread.Sleep(3000);
                        Console.WriteLine("重新链接服务器");
                        Console.WriteLine("======================");
                        StaticLink();
                    }
                    Thread.Sleep(1);
                }
            });
            thread.Start();
            Console.Read();
        }

        static void StaticLink()
        {
            IslinkError = false;
            try
            {
                AsyncCallback asynccallback = new AsyncCallback(StaticSendMsg);
                IAsyncResult result = tcp_pc.BeginConnect("10.0.0.217", 40000, asynccallback, null);
                tcp_pc.EndConnect(result);
                Console.WriteLine("----------------------------------------------");
                Console.WriteLine("客户端连接服务器成功");
                Console.WriteLine("可以向服务端发送消息");
                Console.WriteLine("----------------------------------------------");
                Console.WriteLine("");
            }
            catch (Exception)
            {
                Console.WriteLine("----------------------------------------------");
                Console.WriteLine("客户端连接服务器失败");
                Console.WriteLine("----------------------------------------------");
                Console.WriteLine("");
                IslinkError = true;
                return;
            }
            string ml;
            do
            {
                ml = Console.ReadLine();
                if (ml != "n")
                {
                    try
                    {
                        tcp_pc.Client.Send(Encoding.UTF8.GetBytes(ml));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("与服务端断开链接1");
                        //关闭释放资源
                        tcp_pc.Client.Close();
                        IslinkError = true;
                        break;
                    }
                }

            } while (ml != "n");
            tcp_pc.Client.Close();
        }

        static void StaticSendMsg(IAsyncResult result)
        {
            byte[] bytes = new byte[1024];
            int a = 0;
            do
            {
                try
                {
                    a = tcp_pc.Client.Receive(bytes);
                    if (a > 0)
                    {
                        string b = System.Text.Encoding.UTF8.GetString(bytes, 0, a);
                        Console.WriteLine("客户端:" + b);
                    }
                }
                catch (Exception )
                {
                    IslinkError = true;
                    tcp_pc.Client.Close();
                    Console.WriteLine("与服务端断开链接");
                    return;
                }
            } while (a > 0);
        }
    }
效果:




已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页