C# - 避免让到一个SocketException [英] C# - Avoid getting a SocketException

查看:127
本文介绍了C# - 避免让到一个SocketException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一种方法为避免获得每当我无法连接,而不是使用的try / catch捕捉SocketException SocketException异常。

I was wondering if there's a way to avoid getting a SocketException whenever I cannot connect rather than catching the SocketException using try/catch.

我有这样的代码,检查服务器是否可用,但不是的:

I have this code which checks if a server is available of not:

public bool CheckServerStatus(string IP, int Port)
    {
        try
        {
            IPAddress[] IPs = Dns.GetHostAddresses(IP);

            using (Socket s = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp))
            s.Connect(IPs[0], Port);

            return true;
        }
        catch (SocketException)
        {
            return false;
        }
    }

在此先感谢。

推荐答案

您可以继承插座,并提供具体实现:

You may subclass Socket and provide your specific implementation:

public class MySocket : Socket{
    //...
    public boolean TryConnect(...){
    }
}

您也可以,而不是一个布尔值,返回一个结果对象保存异常错误处理:

You could also instead of a boolean, return a Result object that save the exception for error handling:

public class Result {
    public Exception Error { get; set; }
    public boolean Success { get{ return Error != null; } }
}

这篇关于C# - 避免让到一个SocketException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆