温馨提示×

c# beginreceive能设置超时时间吗

c#
小樊
85
2024-12-04 07:21:51
栏目: 编程语言

是的,在C#中,BeginReceive方法可以设置超时时间。为了实现这个功能,您需要使用Socket类的SetSocketOption方法来设置SocketOptionName.ReceiveTimeout选项。以下是一个示例:

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(ipAddress, port);

            // 设置接收超时时间(单位:毫秒)
            int receiveTimeout = 5000;
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, receiveTimeout);

            byte[] buffer = new byte[1024];
            IAsyncResult result = socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null);

            // 检查是否在超时时间内接收到数据
            if (result.AsyncWaitHandle.WaitOne(receiveTimeout, true))
            {
                int bytesReceived = socket.EndReceive(result);
                string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
                Console.WriteLine("Received data: " + receivedData);
            }
            else
            {
                Console.WriteLine("Receive operation timed out.");
            }
        }
    }
}

在这个示例中,我们首先创建一个Socket对象并连接到指定的IP地址和端口。然后,我们使用SetSocketOption方法设置接收超时时间为5000毫秒(5秒)。接下来,我们使用BeginReceive方法开始接收数据,并使用AsyncWaitHandle.WaitOne方法检查是否在超时时间内接收到数据。如果在超时时间内接收到数据,我们使用EndReceive方法结束接收操作并处理接收到的数据。如果未在超时时间内接收到数据,我们将输出一条超时消息。

0