C# &引用;SocketException:没有已知的主机”;连接到本地主机上的端口时
我知道StackOverflow上已经有几个关于这个特定异常的问题,但我还没有找到解决我的问题的答案 以下是相关的代码片段:C# &引用;SocketException:没有已知的主机”;连接到本地主机上的端口时,c#,.net,tcpclient,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
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;
}
}
在PingCallback(IAsyncResult result)
中的catch
子句中捕获异常,并显示错误消息“不知道这样的主机”
当我运行netstat-an
时,我可以看到我的本地服务器确实在侦听端口311:
如果我更改TcpClient TcpClient=newtcpclient()
toTcpClient TcpClient=新的TcpClient(本地主机,端口)代码>,将在那里引发相同的异常(具有相同的错误消息)
如何解决此问题?主机名指定不正确。当您在没有异步的情况下尝试调用时,您应该有如下类似的调用
TcpClient tcpClient = new TcpClient("127.0.0.1", 31311);
在异步连接中,您应该指定如下内容
tcpClient.BeginConnect(host: "127.0.0.1", ...)
这应该可以修复它您应该提供127.0.0.1
作为本地主机,而不是http://127.0.0.1
@Vikhram谢谢!不知何故,我忽略了它。剥夺睡眠不是开玩笑;-)