📜  c# 套接字连接超时 - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:38.339000             🧑  作者: Mango

代码示例1
public static class SocketExtensions
{
    /// 
    /// Connects the specified socket.
    /// 
    /// The socket.
    /// The IP endpoint.
    /// The timeout.
    public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout)
    {
        var result = socket.BeginConnect(endpoint, null, null);

        bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
        if (success)
        {
            socket.EndConnect(result);
        }
        else
        {
            socket.Close();
            throw new SocketException(10060); // Connection timed out.
        }
    }
}