连接到本地主机上的端口时出现“ SocketException:未知此类主机”

时间:2019-04-15 12:03:14

标签: c# .net tcpclient

我知道StackOverflow上已经有几个问题询问该特定异常,但是我没有找到解决我问题的答案。

以下是相关代码段:

public static class Server
{
    public const string LocalHost = "http://127.0.0.1";
    public const int Port = 31311;
    public static readonly string FullAddress = $"{LocalHost}:{Port}";

    private static readonly TimeSpan RetryConnectionInterval = TimeSpan.FromSeconds(10);

    public static async Task AwaitStart()
    {
        try
        {
            TcpClient tcpClient = new TcpClient();
            ConnectionState connectionState = new ConnectionState(tcpClient);

            tcpClient.BeginConnect(
                host: HostAddress, 
                port: Port,
                requestCallback: PingCallback,
                state: connectionState);

            bool startedSuccessfully = connectionState.IsSuccess;

            while (!startedSuccessfully)
            {
                await Task.Delay(RetryConnectionInterval);
                startedSuccessfully = connectionState.IsSuccess;
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
        }
    }

    private static void PingCallback(IAsyncResult result)
    {
        ConnectionState state = (ConnectionState)result.AsyncState;

        try
        {
            state.TcpClient.EndConnect(result);
            state.IsSuccess = true;
            Console.WriteLine("The server is successfully started.");
        }
        catch (SocketException)
        {
            Console.WriteLine($"The server is not yet started. Re-attempting connection in {RetryConnectionInterval.Seconds} seconds.");

            Wait(RetryConnectionInterval).GetAwaiter().GetResult();
            state.TcpClient.BeginConnect(host: HostAddress, port: Port, requestCallback: PingCallback, state: state);
        }
    }

    private static async Task Wait(TimeSpan duration)
    {
        await Task.Delay(duration);
    }
}

public class ConnectionState
{
    public bool IsSuccess;
    public readonly TcpClient TcpClient;

    public ConnectionState(TcpClient tcpClient)
    {
        this.TcpClient = tcpClient;
    }
}

该异常捕获在catch的{​​{1}}子句中,并显示错误消息“未知此类主机”。

运行PingCallback(IAsyncResult result)时,我可以看到本地服务器确实在侦听端口31311:

enter image description here

如果我将netstat -an更改为TcpClient tcpClient = new TcpClient();,则会在此处引发相同的异常(带有相同的错误消息)。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

主机名指定错误。尝试在不使用异步的情况下进行通话应该如下所示。

TcpClient tcpClient = new TcpClient("127.0.0.1", 31311);

在异步连接中,您应指定以下内容

tcpClient.BeginConnect(host: "127.0.0.1", ...)

这应该解决