C#异步Tcp通讯客户端

基本步骤

~ 创建套接字并保证与服务器的端口一致

~ 使用BeginConnect()和EndConnect()这组方法向服务端发送连接请求

~ 使用BeginSend()/EndSend和BeginReceive()/EndReceive()两组方法与服务端进行收发通信

~ 关闭套接字

代码实现


        #region 客户端tcp通讯
        public class StateObject
        {
            // 当前客户端的Socket
            public Socket workSocket = null;
            // 可接收的最大字节数
            public const int BufferSize = 1024 * 1024;
            // 接收的数据存储
            public byte[] buffer = new byte[BufferSize];
        }

        //内存缓存区
        public static List<byte> RevBuf;
        public static bool _BoolRevContent = false;
        public static bool BoolRevContent
        {
            get { return _BoolRevContent; }
            set { _BoolRevContent = value; }
        }
        public static Socket clientT;
        public static IPEndPoint serverPoint = null;
        /// <summary>
        /// 连接服务端
        /// </summary>
        /// <param name="ip">Ip</param>
        /// <param name="port">端口</param>
        public bool ConnectServercer(string ip, string port)
        {
            IPAddress IP = IPAddress.Parse(ip.Trim());
            serverPoint = new IPEndPoint(IP, Convert.ToInt32(port));
            try
            {
                clientT = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建套接字
                clientT.BeginConnect(serverPoint, new AsyncCallback(ConnectCallback), clientT);//异步回调发送连接请求
                //clientT.Connect(Point);
                Thread.Sleep(500);//异步等500毫秒返回连接结果
                return clientT.Connected;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private  void ConnectCallback(IAsyncResult ar) //连接客户端异步回调
        {
            Socket client = (Socket)ar.AsyncState;
            try
            {
                if (client != null && client.Connected)
                {
                    client.EndConnect(ar);//BeginConnect对应EndConnect
                    Receive(client);
                }
                else
                {
                    label4.Text = "服务端未开启";
                    client.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
        //接收消息
        private  void Receive(Socket client)
        {
            StateObject state = new StateObject();
            state.workSocket = client;
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);//异步回调接收服务端消息
        }
        //接收消息异步回调
        private  void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;
            try
            {
                if (client != null && clientT.Connected)
                {
                    int bytesRead = client.EndReceive(ar);
                    if (bytesRead > 0)//读取到服务端发送过来的字节长度
                    {
                        BoolRevContent = true;
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                        byte[] ActConn = new byte[bytesRead];
                        Buffer.BlockCopy(state.buffer, 0, ActConn, 0, bytesRead);//将接收到的byte复制接收到的字节长度到新的byte集合中
                      //这里可以数据处理
                        RevBuf = new List<byte>();
                        RevBuf.AddRange(ActConn);//将接收到的消息的字节添加到新的list<byte>中
                        BoolRevContent = false;
                    }
                    else
                    {
                        label4.Text = "服务端断开连接";
                    }
                }
                else
                {
                    label4.Text = "服务端断开连接";
                }
            }
            catch (Exception ex)
            {
                
                label4.Text = "服务端异常断开连接";
            }
            
        }
        /// <summary>
        /// 向服务端发送消息
        /// </summary>
        /// <param name="sendMsg"></param>
        public static void Send(string sendmessage)
        {
            try
            {
                if (clientT != null && clientT.Connected)
                {
                    byte[] data = DataTypeConverter.HexStringToByteArray(sendmessage);
                    clientT.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), clientT);
                }
            }
            catch (Exception ex)
            {
            }
        }
        //发送消息异步回调
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // 从异步状态中检索socket
                Socket client = (Socket)ar.AsyncState;
                // 完成将数据发送到服务端
                int bytesSent = client.EndSend(ar);
                // 表示所有自己均已发送
                //sendDone.Set();
            }
            catch (Exception ex)
            {
            }
        }
        #endregion
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个简单的C#异步TCP客户端,带有回调函数来处理数据: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class AsyncTcpClient { private TcpClient _client; private byte[] _buffer = new byte[1024]; public void Connect(string host, int port, Action<string> callback) { _client = new TcpClient(); _client.BeginConnect(host, port, ar => { _client.EndConnect(ar); callback("Connected to " + host + ":" + port); StartReading(); }, null); } public void Send(string message) { byte[] data = Encoding.UTF8.GetBytes(message); _client.GetStream().BeginWrite(data, 0, data.Length, ar => { _client.GetStream().EndWrite(ar); }, null); } private void StartReading() { _client.GetStream().BeginRead(_buffer, 0, _buffer.Length, ar => { int bytesRead = _client.GetStream().EndRead(ar); string message = Encoding.UTF8.GetString(_buffer, 0, bytesRead); OnMessageReceived(message); StartReading(); }, null); } private void OnMessageReceived(string message) { Console.WriteLine("Received message: " + message); } public void Disconnect() { _client.Close(); } } ``` 使用示例: ```csharp var client = new AsyncTcpClient(); client.Connect("127.0.0.1", 8888, message => { Console.WriteLine(message); }); client.Send("Hello, server!"); Console.ReadLine(); client.Disconnect(); ``` 在这个例子中,我们创建了一个异步TCP客户端,它连接到指定的主机和端口。当连接成功时,回调函数被调用并显示连接消息。我们还可以使用`Send`方法向服务器发送消息。当我们收到来自服务器的消息时,回调函数`OnMessageReceived`被调用。最后,我们使用`Disconnect`方法关闭连接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值