c# TcpClient 客户端断线重连类库

初始化未连接到服务器重新连接

发送消息失败重新连接,

断线重新连接

欢迎测试,分享使用!

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;

namespace MyTcpClient
{
    //规范命名、添加注释、合理封装、限制访问权限    
    public class AsyncTcpClient
    {
        private string ip1;
        private int port1;
        byte[] ReadBytes = new byte[1024];
        //单例
        TcpClient tcpClient;
        //连接服务器
        public void ConnectServer(string ip, int port)
        {
            //防止多个事例去重复连接
            if (isTryingToCon == true)
            {
                return;
            }
            ip1 = ip;
            port1 = port;
            try
            {
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
                tcpClient = new TcpClient();
                isTryingToCon = true;
                //开始异步
                tcpClient.BeginConnect(IPAddress.Parse(ip), port, Lianjie, null);
            }
            catch (Exception e)
            {
            }
        }
        private bool isTryingToCon = false;
        //连接判断
        void Lianjie(IAsyncResult ar)
        {
            if (IsClose)
            {
                return;
            }
            if (tcpClient.Connected == false)
            {
                SetCon(0);
                tcpClient.Close();
                tcpClient = new System.Net.Sockets.TcpClient();
                //尝试重连。。。。。。;
                tcpClient.BeginConnect(IPAddress.Parse(ip1), port1, Lianjie, null);
            }
            else
            {
                //连接上了
                isTryingToCon = false;
                //结束异步连接
                tcpClient.EndConnect(ar);
                //读取数据
                tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
                SetCon(1);
            }
        }


        //接收消息
        void ReceiveCallBack(IAsyncResult ar)
        {
            try
            {
                int len = tcpClient.GetStream().EndRead(ar);//结束异步读取
                if (len > 0)
                {
                    MyEventArgs e = new MyEventArgs(ip1, ReadBytes);
                    _MsgChange(e);
                    //重置数据,防止旧数据残留
                    ReadBytes = new byte[1024];
                    tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
                }
                else
                {
                    //尝试重连。。。。。。"
                    ConnectServer(ip1, port1);
                }
            }
            catch (Exception e)
            {
            }
        }

        //发送消息
        public bool SendMsg(string msg)
        {
            try
            {
                //开始异步发送
                byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
                tcpClient.GetStream().BeginWrite(msgBytes, 0, msgBytes.Length, (ar) =>
                {
                    tcpClient.GetStream().EndWrite(ar);//结束异步发送
                }, null);
                return true;
            }
            catch (Exception ex)
            {
                // int a = ex.NativeErrorCode;
                //尝试重连。。。。。。"
                ConnectServer(ip1, port1);
                return false;
            }
        }
        public bool SendMsg(byte[] msg)
        {
            try
            {
                //开始异步发送
                tcpClient.GetStream().BeginWrite(msg, 0, msg.Length, (ar) =>
                {
                    tcpClient.GetStream().EndWrite(ar);//结束异步发送
                }, null);
                return true;
            }
            catch (Exception ex)
            {
                //尝试重连。。。。。。"
                ConnectServer(ip1, port1);
                return false;
            }
        }
        bool IsClose = false;
        /// 
        /// 断开连接
        /// 
        public void Close()
        {
            IsClose = true;
            if (tcpClient != null && tcpClient.Client.Connected)
            {
                tcpClient.Close();
            }
            if (!tcpClient.Client.Connected)
            {
                tcpClient.Close();//断开挂起的异步连接
            }
        }
        int isConnected = -1;
        /// 
        /// -1 初始化  0 未连接  1 连接
        /// 
        /// 
        private void SetCon(int _con)
        {
            if (isConnected != _con)
            {
                bool rel = false;
                if (_con == 1)
                {
                    rel = true;
                }
                isConnected = _con;
                MyEventArgs e = new MyEventArgs(ip1, rel);
                _ConChange(e);
            }
        }


        public class MyEventArgs : EventArgs
        {
            public string IP;
            public bool IsConnetct;
            public byte[] Msg;
            public MyEventArgs(string iP, byte[] msg)
            {
                IP = iP;
                Msg = msg;
            }
            public MyEventArgs(string iP, bool iscon)
            {
                IP = iP;
                IsConnetct = iscon;
            }
        }
        //连接状态
        public delegate void ConChange(object sender, MyEventArgs args);
        public event ConChange OnConChange;
        protected virtual void _ConChange(MyEventArgs e)
        {
            if (OnConChange != null)
            {
                OnConChange(this, e);
            }
        }
        //收到的消息
        public delegate void MsgChange(object sender, MyEventArgs args);
        public event MsgChange OnMsgChange;
        protected virtual void _MsgChange(MyEventArgs e)
        {
            if (OnMsgChange != null)
            {
                OnMsgChange(this, e);
            }
        }
    }
}

调用方法

        AsyncTcpClient sw = new AsyncTcpClient();
        private void Form1_Load(object sender, EventArgs e)
        {
            sw.ConnectServer("192.168.1.19", 8000);
            sw.OnConChange += Sw_OnConChange;
            sw.OnMsgChange += Sw_OnMsgChange;
        }

        private void Sw_OnMsgChange(object sender, AsyncTcpClient.MyEventArgs args)
        {
            string str = Encoding.UTF8.GetString(args.Msg, 0, args.Msg.Length);
            str = Uri.UnescapeDataString(str);
            Invoke(new MethodInvoker(delegate ()
            {
                label2.Text = args.IP + "___" + str;
            }));

        }

        private void Sw_OnConChange(object sender, AsyncTcpClient.MyEventArgs args)
        {
            Invoke(new MethodInvoker(delegate ()
            {
                label1.Text = args.IP + "___" + args.IsConnetct.ToString();
            }));
        }

        private void button1_Click(object sender, EventArgs e)
        {

           bool rel= sw.SendMsg("asdf");
            button1.Text = rel.ToString();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            sw.OnConChange -= Sw_OnConChange;
            sw.OnMsgChange -= Sw_OnMsgChange;
            sw.Close();

        }

测试出Gug后请留言,万分感谢!!!

C#断线重现升级版 有接收字符分割功能.

你可能感兴趣的:(c#,服务器,开发语言)