.NET Tcp侦听器停止方法不会在存在子进程时停止侦听器

本文关键字:侦听器 存在 子进程 方法 Tcp NET | 更新日期: 2023-09-27 18:33:41

我正在使用一些遗留的TCP服务器代码,这些代码直接与套接字一起使用,因为它是在.NET 2.0及更早版本中编写的。服务器具有"停止"和"启动"接受客户端连接的功能。

为了解决问题,我以管理员用户身份在控制台模式下运行服务器。最重要的是,我已经从等式中删除了套接字接受线程,所有代码的作用是这样的:

tcpListener = new TcpListener(IPAddress.Any, this.Port);
tcpListener.Start();

tcpListener.Stop();

这是从不同的方法调用的。我已经调试了代码,我很确定代码只执行一次。但是,问题是对Stop的调用实际上并没有释放套接字地址,因此随后对Start的调用失败,并显示错误"通常只允许每个套接字地址(协议/网络地址/端口(使用一次"。我还可以从进程资源管理器确认服务器仍在侦听服务器端口。

当我编写一个使用相同的代码片段的小型控制台应用程序时,一切正常。我什至尝试跟踪 .NET 网络和套接字库,但没有错误或任何迹象表明那里存在问题。

我不清楚为什么调用Stop不释放套接字地址?

更新:经过更多的调查,事实证明,子进程启动到TcpListener有一些奇怪的影响。我制作了一个"裸骨"示例代码来说明这个问题:

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
namespace TcpListenerStartStop
{
    class MyTcpListener
    {
        public static void Main(string[] args)
        {
            Int32 port = 13000;
            if (args.Length > 0) // indicates child process
            {
                Thread.Sleep(4000); // as a child do nothing and wait for a few seconds
            }
            else // parent will play with the TcpListener
            {
                //LaunchChildProcess(); // launch child here and listener restart is fine?!?
                var tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();
                Console.WriteLine("Starting test in 2 seconds...");
                Thread.Sleep(2000);
                LaunchChildProcess(); // launch child here and listener restart is not fine?!?
                tcpListener.Stop();
                Console.WriteLine("Stopped.");
                Thread.Sleep(1000);
                tcpListener.Start();
                Console.WriteLine("Started");
            }
            Console.WriteLine("All is good, no exceptions :)");
        }
        private static void LaunchChildProcess()
        {
            Process process = new Process();
            var processStartInfo = new ProcessStartInfo
            {
                CreateNoWindow = true,
                FileName = Assembly.GetExecutingAssembly().Location,
                UseShellExecute = false, // comment out this line out listener restart is fine?!?
                Arguments = "child"
            };
            process.StartInfo = processStartInfo;
            process.Start();
        }
    }
}

从代码中可以看出,如果我在创建侦听器之前启动子进程,如果我在侦听器重新启动失败后执行此操作,一切都很好。这与子进程的UseShellExecute = false选项有关。

不确定这是 .NET 错误还是我不知道的一些特殊行为?

.NET Tcp侦听器停止方法不会在存在子进程时停止侦听器

此行为的真正原因是TcpListener套接字句柄与许多其他句柄一起由子进程继承。关于该主题的一些讨论可以在这里和这里找到。

一个明显的解决方案是在初始化TcpListener之前启动子进程。

另一种解决方案是使用UseShellExecute = true以避免此套接字句柄继承。

理想的解决方案是设置套接字句柄选项以防止子进程继承。可以通过 TcpListener 套接字句柄上的 P/Invoke 在 .NET 中执行此操作:

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetHandleInformation(IntPtr hObject, uint dwMask, uint dwFlags);
    private const uint HANDLE_FLAG_INHERIT = 1;
    private static void MakeNotInheritable(TcpListener tcpListener)
    {
        var handle = tcpListener.Server.Handle;
        SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
    }