number007cool 2021-09-13 16:47 采纳率: 20%
浏览 90

C# tcpClient 异步怎样判定数据发送成功,怎样判定异常断开,用的哪几个API,网上搜一大堆,没找到好资料



```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;


namespace tcpClientAsync
{
    public class Pub_TcpClientAsync
    {
        private TcpClient tcpClient;

        private NetworkStream networkStream;

        public string remoteIp = string.Empty;

        public int remotePort = -1;

        public bool bConnected = false;

        public delegate void dlg_Parse(byte[] data, int len);

        public dlg_Parse m_dlgParse;

        public void set_dlgParseHook(dlg_Parse parse)
        {
            m_dlgParse = parse;
        }

        /// <summary>
        /// 返回数据
        /// </summary>
        public List<byte[]> ResponseBytes = new List<byte[]>();


        /// <summary>
        /// 主动和服务器建立连接
        /// </summary>
        public void ConnectToServer()
        {
            //if (tcpClient == null)
            {
                tcpClient = new TcpClient();
            }

            tcpClient.BeginConnect(remoteIp, remotePort, new AsyncCallback(AsynConnectCb), tcpClient);
        }


        /// <summary>
        /// 主动和服务器建立连接
        /// </summary>
        public void DisConnectToServer()
        {
            if (tcpClient != null && tcpClient.Client.Connected)
            {
                tcpClient.Close();
            }
            if (!tcpClient.Client.Connected)
            {
                tcpClient.Close();//断开挂起的异步连接
            }
        }


        public void AsynConnectCb(IAsyncResult iar)
        {
            try
            {
                //连接成功
                tcpClient.EndConnect(iar);
                //连接成功标志
                bConnected = true;
                networkStream = tcpClient.GetStream();
                byte[] TempBytes = new byte[1024];
                //开始异步读取返回数据
                networkStream.BeginRead(TempBytes, 0, TempBytes.Length, new AsyncCallback(AsynReceiveDataCb), TempBytes);

                Console.WriteLine("连接成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERROR] AsynConnectCb");
            }
        }


        public void printBytes(byte[] bdata, int len)
        {
            Console.Write("recv: " + len + ",");
            for (int i = 0; i < len; i++)
            {
                string strT = String.Format("{0:X2} ", bdata[i]);
                Console.Write(strT);
            }
            Console.WriteLine("");
        }

        /// <summary>
        /// 异步接受数据
        /// </summary>
        /// <param name="iar"></param>
        public void AsynReceiveDataCb(IAsyncResult iar)
        {
            byte[] CurrentBytes = (byte[])iar.AsyncState;
            try
            {
                //结束了本次数据接收
                int num = networkStream.EndRead(iar);

                if (num <= 0) return;

                //这里展示结果为InfoModel的CurrBytes属性,将返回的数据添加至返回数据容器中
                ResponseBytes.Add(CurrentBytes);
                //处理结果后马上启动数据异步读取【目前我每条接收的字节数据长度不会超过1024】
                byte[] NewBytes = new byte[1024];
                networkStream.BeginRead(NewBytes, 0, NewBytes.Length, new AsyncCallback(AsynReceiveDataCb), NewBytes);

                printBytes(CurrentBytes, num);

                if (m_dlgParse != null)
                {
                    m_dlgParse(CurrentBytes, num);
                }
                //Console.WriteLine("recv " + num + " bytes");
            }
            catch (Exception ex)
            {
                //VerficationOperate.WriteTextLogs("TcpClientBusiness", "AsynReceiveData|异常消息:" + ex.Message.ToString());
            }
        }



        /// <summary>
        /// 发送数据
        /// <param name="SendBytes">需要发送的数据</param>
        /// </summary>
        public void SendData(byte[] SendBytes)
        {
            try
            {
                if (networkStream.CanWrite && SendBytes != null && SendBytes.Length > 0)
                {
                    //发送数据
                    //networkStream.Write(SendBytes, 0, SendBytes.Length);
                    //networkStream.Flush();

                    networkStream.BeginWrite(SendBytes, 0, SendBytes.Length, new AsyncCallback(SendCallback), networkStream);
                }
            }
            catch (Exception ex)
            {
                if (tcpClient != null)
                {
                    tcpClient.Close();
                    //关闭连接后马上更新连接状态标志
                    bConnected = false;

                    Console.WriteLine("发送异常,tcp断开");
                }
                //VerficationOperate.WriteTextLogs("TcpClientBusiness", "SendData|异常消息:" + ex.Message.ToString());
            }
        }

        private static void SendCallback(IAsyncResult ar)
        {
            Console.WriteLine("do ????");
        }


    }//end class
}//end namespace


```

  • 写回答

1条回答 默认 最新

  • 於黾 2021-09-13 16:52
    关注

    你既然用c#,语法里已经给你提供了tcpclient,不要自己引用socket去实现了啊
    你用try...catch包住,如果异常断开自然给你抛出相应的错误

    评论

报告相同问题?

问题事件

  • 创建了问题 9月13日

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错