在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 = https://www.yisu.com/ask/Encoding.ASCII.GetString(socket.ReceiveBuffer, 0, bytesReceived);"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
异常来处理连接断开。