C#中使用TcpClient進(jìn)行異步通信的方法

c#
小樊
93
2024-08-29 20:13:47

在C#中,使用TcpClient進(jìn)行異步通信的方法主要包括以下幾個(gè)步驟:

  1. 創(chuàng)建一個(gè)TcpClient實(shí)例。
  2. 使用BeginConnect方法異步連接到服務(wù)器。
  3. 使用BeginReadBeginReceive方法異步讀取數(shù)據(jù)。
  4. 使用BeginWriteBeginSend方法異步發(fā)送數(shù)據(jù)。
  5. 使用EndConnectEndReadEndReceive、EndWriteEndSend方法完成異步操作。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何使用TcpClient進(jìn)行異步通信:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TcpClientAsyncExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建一個(gè)TcpClient實(shí)例
            TcpClient client = new TcpClient();

            // 異步連接到服務(wù)器
            client.BeginConnect("127.0.0.1", 8080, ConnectCallback, client);
        }

        static void ConnectCallback(IAsyncResult ar)
        {
            TcpClient client = (TcpClient)ar.AsyncState;

            try
            {
                // 完成異步連接
                client.EndConnect(ar);

                Console.WriteLine("Connected to server.");

                // 異步讀取數(shù)據(jù)
                byte[] buffer = new byte[1024];
                client.GetStream().BeginRead(buffer, 0, buffer.Length, ReadCallback, new object[] { client, buffer });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error connecting to server: " + ex.Message);
            }
        }

        static void ReadCallback(IAsyncResult ar)
        {
            object[] state = (object[])ar.AsyncState;
            TcpClient client = (TcpClient)state[0];
            byte[] buffer = (byte[])state[1];

            try
            {
                // 完成異步讀取
                int bytesRead = client.GetStream().EndRead(ar);

                if (bytesRead > 0)
                {
                    string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received data: " + receivedData);

                    // 異步發(fā)送數(shù)據(jù)
                    byte[] sendBuffer = Encoding.UTF8.GetBytes("Hello from client!");
                    client.GetStream().BeginWrite(sendBuffer, 0, sendBuffer.Length, WriteCallback, client);
                }
                else
                {
                    Console.WriteLine("Server disconnected.");
                    client.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error reading data: " + ex.Message);
            }
        }

        static void WriteCallback(IAsyncResult ar)
        {
            TcpClient client = (TcpClient)ar.AsyncState;

            try
            {
                // 完成異步發(fā)送
                client.GetStream().EndWrite(ar);

                Console.WriteLine("Data sent to server.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending data: " + ex.Message);
            }
        }
    }
}

這個(gè)示例展示了如何使用TcpClient進(jìn)行異步連接、讀取和發(fā)送數(shù)據(jù)。請(qǐng)注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要根據(jù)需求進(jìn)行調(diào)整。

0