• C#异步TCP客户端连接


    前言:C#平常的TCP客户端连接不稳定,时常断线,这时我使用了异步连接之后就没有断线了。

    旧连接代码:

    //创建用于通讯的socket
     PlcClass.Instance.socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPAddress ip = IPAddress.Parse(BaseData.Instance.tcp_ip);
     IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(BaseData.Instance.tcp_port));
     //连接对应的端口
     PlcClass.Instance.socketsend.Connect(port);
     // 接收信息
     byte[] buffer = new byte[1024 * 1024 * 2];
     int i = socketsend.Receive(buffer);
     string str = Encoding.UTF8.GetString(buffer, 0, i);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    新异步连接代码

    TcpClient tcpClient;
    byte[] ReadBytes = new byte[1024 * 1024];
    //连接服务器
    public void ConnectServer(string ip, int port)//填写服务端IP与端口
    {
        try
        {
            tcpClient = new System.Net.Sockets.TcpClient();//构造Socket
            tcpClient.BeginConnect(IPAddress.Parse(ip), port, Lianjie, null);//开始异步
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
    
    //连接判断
    void Lianjie(IAsyncResult ar)
    {
        try
        {
            if (!tcpClient.Connected)
            {
                IPAddress ip = IPAddress.Parse(BaseData.Instance.tcp_ip);
                tcpClient.BeginConnect(ip, Convert.ToInt32(BaseData.Instance.tcp_port), Lianjie, null);
            }
            else
            {
                tcpClient.EndConnect(ar);//结束异步连接
                tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("连接失败:" + ex.Message);
        }
       
    }
    
    
    //接收消息
    void ReceiveCallBack(IAsyncResult ar)
    {
        try
        {
            int len = tcpClient.GetStream().EndRead(ar);//结束异步读取
            if (len > 0)
            {
                string str = Encoding.UTF8.GetString(ReadBytes, 0, len);
                str = Uri.UnescapeDataString(str);
                ,...逻辑处理....
                tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
            }
            else
            {
                tcpClient = null;
                ConnectServer(BaseData.Instance.tcp_ip, Convert.ToInt32(BaseData.Instance.tcp_port));
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
    
    //发送消息
    public void SendMsg(string msg)
    {
        try
        {
            byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
            tcpClient.GetStream().BeginWrite(msgBytes, 0, msgBytes.Length, (ar) => {
                tcpClient.GetStream().EndWrite(ar);//结束异步发送
            }, null);//开始异步发送
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
       
    }
    
    /// <summary>
    /// 断开连接
    /// </summary>
    public void TcpClose()
    {
        try
        {
            if (tcpClient != null && tcpClient.Client.Connected)
                tcpClient.Close();
            if (!tcpClient.Client.Connected)
            {
                tcpClient.Close();//断开挂起的异步连接
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
       
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
  • 相关阅读:
    每天一个数据分析题(一百八十三)
    百度百家号旋转验证码识别研究
    WPFdatagrid结合comboBox
    正则表达式在java里的运用
    1 动态规划
    C语言 每日一题 PTA 10.28 day6
    Spring的注解总结
    【开源】JAVA+Vue.js实现农家乐订餐系统
    npm私有云
    SpringCache
  • 原文地址:https://blog.csdn.net/huatoudd/article/details/125633341