温馨提示×

c# beginreceive在哪处理连接断开

c#
小樊
84
2024-12-04 07:28:52
栏目: 编程语言

在C#中,BeginReceive方法用于异步接收数据。当连接断开时,BeginReceive方法会抛出一个SocketException异常。为了处理连接断开,你需要在调用BeginReceive时提供一个回调方法,该方法会处理SocketException异常。

以下是一个简单的示例,展示了如何在BeginReceive的回调方法中处理连接断开:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 12345;

        using (Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
        {
            socket.Connect(new IPEndPoint(ipAddress, port));

            // 发送数据
            string message = "Hello, Server!";
            byte[] sendBytes = Encoding.ASCII.GetBytes(message);
            socket.Send(sendBytes);

            // 开始接收数据
            socket.BeginReceive(new byte[1024], 0, 1024, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);

            // 等待用户输入,以便在按下回车键后关闭套接字
            Console.WriteLine("Press ENTER to close the connection...");
            Console.ReadLine();
        }
    }

    static void ReceiveCallback(IAsyncResult ar)
    {
        Socket socket = (Socket)ar.AsyncState;

        try
        {
            // 接收数据
            int bytesReceived = socket.EndReceive(ar);
            if (bytesReceived > 0)
            {
                string receivedData = Encoding.ASCII.GetString(socket.ReceiveBuffer, 0, bytesReceived);
                Console.WriteLine("Received data: " + receivedData);

                // 继续接收数据
                socket.BeginReceive(new byte[1024], 0, 1024, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            }
            else
            {
                // 处理连接断开
                Console.WriteLine("Connection closed.");
            }
        }
        catch (SocketException ex)
        {
            // 处理连接断开
            Console.WriteLine("SocketException: " + ex.Message);
        }
    }
}

在这个示例中,我们首先创建一个Socket对象并连接到服务器。然后,我们使用BeginReceive方法开始异步接收数据。在回调方法ReceiveCallback中,我们尝试使用EndReceive方法接收数据。如果EndReceive返回0,表示连接已断开。在这种情况下,我们可以捕获SocketException异常来处理连接断开。

0