首页 > 解决方案 > 连接到本地主机上的端口时出现“SocketException:不知道这样的主机”

问题描述

我知道 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子句中被捕获PingCallback(IAsyncResult result),并带有错误消息“No such host is known”。

当我运行时netstat -an,我可以看到我的本地服务器确实在侦听端口 31311:

在此处输入图像描述

如果我更改TcpClient tcpClient = new TcpClient();TcpClient tcpClient = new TcpClient(LocalHost, Port);,则会在此处引发相同的异常(具有相同的错误消息)。

我该如何解决这个问题?

标签: c#.nettcpclient

解决方案


主机名指定不正确。当你在没有异步的情况下尝试它时,你应该有类似下面的调用。

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

在异步连接中,您应该指定如下

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

这应该解决它


推荐阅读