我开发了一个TCP侦听器。以下是侦听器的主要编码:
public static void GetXMLStream()
{
TcpListener lisetner = null;
try
{
Int32 port = Int32.Parse(AppConfigValues.GetAppConfigValue("Port"));
IPAddress localAddr = IPAddress.Parse(AppConfigValues.GetAppConfigValue("IPAddress"));
lisetner = new TcpListener(localAddr, port);
MIEventLogs.WriteLog("trying to Start");
lisetner.Start();
MIEventLogs.WriteLog("Started");
while (true)
{
//TcpClient client = await server.AcceptTcpClientAsync(); //For future purpose only.
//await Task.Run(async () => await ProcessClient(client));
TcpClient client = lisetner.AcceptTcpClient();
MIEventLogs.WriteLog("Accepted new client with IP : "+ ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString()+" Port: "+ ((IPEndPoint)client.Client.RemoteEndPoint).Port.ToString());
ThreadPool.QueueUserWorkItem(ProcessClient, client);
}
}
catch (SocketException e)
{
MIEventLogs.WriteLog("SocketException: {0}" + e);
}
finally
{
lisetner.Stop();
}
}
我运行了这段代码--通过传递部署在其上的系统的IPAddress,这在本地运行得很好。
现在,我们将它部署在一个prod服务器上,它还通过传递部署它的服务器的IPAddress来处理这个prod服务器。
现在,通过传递部署它的服务器的IPAddress,我们将它部署在另一个prod服务器上,这里它正在抛出错误:
SocketException:{0}System.Net.Sockets.SocketException (0x80004005):请求的地址在其上下文中无效。
这个错误总是出现在lisetner.Start()上;
现在我做了下面的分析:
中传递的相同。
我担心的是为什么服务器的确切ip不能工作,而IPAddress.Any正在工作,另一方面,另外两台服务器在IP地址上运行良好,IPAddress.Any和0.0.0.0是
发布于 2022-08-24 10:16:19
在我的例子中,我做了更多的分析,发现只有当我重新启动系统并且服务启动类型是自动的时,这个异常才会出现。如果我将服务启动类型自动更改为手动和重新启动系统,它总是工作正常。因此,简单地说,它与IP地址分配有关。由于启动服务立即启动,但网络连接反过来IP分配需要时间。现在我设置了Startup自动(延迟启动),它运行良好。
发布于 2022-08-21 08:54:30
我不知道为什么它不能与服务器的确切IP地址工作。您可能没有正确地输入地址,或者它是次要地址或其他什么的。
尽管如此,您应该始终使用IPAddress.Any
,或者从连接的网络接口列表中提供用户选项。无法绑定到未连接的接口。
另外,您应该将其转换为完全的async
代码。
public static async Task GetXMLStream(CancellationToken token)
{
TcpListener listener = null;
try
{
Int32 port = Int32.Parse(AppConfigValues.GetAppConfigValue("Port"));
listener = new TcpListener(IPAddress.Any, port);
MIEventLogs.WriteLog("trying to Start");
listener.Start();
MIEventLogs.WriteLog("Started");
while (true)
{
TcpClient client = await listener.AcceptTcpClientAsync(token);
MIEventLogs.WriteLog("Accepted new client with IP : "+ ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString()+" Port: "+ ((IPEndPoint)client.Client.RemoteEndPoint).Port.ToString());
Task.Run(async () => await ProcessClient(client, token));
// make sure ProcessClient disposes the client
}
catch (SocketException e)
{
MIEventLogs.WriteLog("SocketException: {0}" + e);
}
catch (OperationCanceledException)
{ //
}
finally
{
listener.Stop();
}
}
}
https://stackoverflow.com/questions/73424004
复制相似问题