DotNet Core 2:HttpListener无法在Ubuntu

时间:2017-10-27 10:20:21

标签: ubuntu .net-core httplistener

以下使用HTTPListener的DotNet Core 2项目在Windows上运行时有效,但在Ubuntu上运行时会抛出HttpListenerException。

    static void Main(string[] args)
    {
        Console.WriteLine("Started.");

        HttpListener listener = new HttpListener();

        listener.Prefixes.Add(@"http://+:83/");

        listener.Start();


        ThreadPool.QueueUserWorkItem((c) =>
        {
            Console.WriteLine("Webserver processing...");
        }, listener.GetContext());

        listener.Stop();

        listener.Close();
        Console.WriteLine("Stopped.");
    }

在Windows上,我运行该过程然后浏览。该流程无怨无悔地退出:

Started.
Webserver processing...
Stopped.

但是在Ubuntu上,我运行该过程,然后浏览:

Started.
Webserver processing...

Unhandled Exception: System.Net.HttpListenerException: Address already in use 
at System.Net.HttpEndPointManager.GetEPListener(String host, Int32 port, HttpListener listener, Boolean secure)
at System.Net.HttpEndPointManager.RemovePrefixInternal(String prefix, HttpListener listener)
at System.Net.HttpEndPointManager.RemoveListener(HttpListener listener)
at System.Net.HttpListener.Close(Boolean force)
at System.Net.HttpListener.Dispose()
at System.Net.HttpListener.Close()
at ListenTest.Program.Main(String[] args) in Program.cs:line 30
Aborted

因此它会抛出listener.Close()。

我可以捕获HttpListenerException并忽略它,但是下次我运行该进程时会在listener.Start()上抛出相同的错误和消息。因为它在我第一次运行它时没有释放套接字,所以我需要等待一两分钟才能在操作系统释放套接字/端口之前重复使用。

如果我注释掉ThreadPool.QueueUserWorkItem()调用,要禁止浏览到端口,那么程序会很好地退出而不会抛出。

任何关于让它在Ubuntu上运行的想法都将不胜感激! :)

更新 这应该在.NetCore 2.1.0(根据https://github.com/dotnet/corefx/issues/25016

中修复

1 个答案:

答案 0 :(得分:1)

这应该在.NetCore 2.1.0(根据https://github.com/dotnet/corefx/issues/25016

中修复