.NET TcpListener Stop 方法在有子进程时不停止监听器

Slo*_*vic 5 c# sockets tcp tcplistener child-process

我正在使用一些传统的 TCP 服务器代码,这些代码直接与套接字一起工作,因为它是在 .NET 2.0 及更早版本中编写的。服务器具有“停止”和“开始”接受客户端连接的功能。

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

tcpListener = new TcpListener(IPAddress.Any, this.Port);
tcpListener.Start();
Run Code Online (Sandbox Code Playgroud)

tcpListener.Stop();
Run Code Online (Sandbox Code Playgroud)

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

当我编写一个使用相同代码片段的小型控制台应用程序时,一切正常。我什至尝试跟踪 .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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Slo*_*vic 5

这种行为的真正原因是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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 好问题,好答案!很好的重现示例 (2认同)