c# - 连接到本地主机上的端口时出现“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);
,则会在此处引发相同的异常(具有相同的错误消息)。
我该如何解决这个问题?
解决方案
主机名指定不正确。当你在没有异步的情况下尝试它时,你应该有类似下面的调用。
TcpClient tcpClient = new TcpClient("127.0.0.1", 31311);
在异步连接中,您应该指定如下
tcpClient.BeginConnect(host: "127.0.0.1", ...)
这应该解决它
推荐阅读
- python - 我在使用基本 Python 语法时遇到问题
- stl - 使用自定义比较器设置的 C++ STL
- c# - 在c#中查看Pdf文件或任何其他文件的二维码
- r - R:求和时的错误?
- python - 训练测试拆分以确保所有类别都包含在训练集中
- php - 如何使用 GoDaddy 连接数据库?
- azure-devops - 如何在 Ymal 文件中获取动态生命周期服务资产上传 (LCS) 的资产类型和引用变量名称和值
- reactjs - 如何将redux存储持久化到本地存储而不是反应原生的异步存储
- python - python动态继承类
- android - 我的 Android 应用程序允许第一次 google 登录,之后它提供以下错误 ApiException:10: