首页 > 解决方案 > 一段时间后 HttpListener 似乎失去了连接

问题描述

我对 C# 编程相当陌生,我正在尝试与一个提供通过 uri 发送数据的接口的程序进行交互。到目前为止,这很好用,但大约 1-2 分钟后,程序仍在发送数据,但我的控制台应用程序不再识别它。

顺便说一句,这是我关于stackoverflow的第一个问题,所以请耐心等待:)

该程序有一个字段用于输入网络服务器的 uri,程序的状态更新以 json 格式发送到该服务器。在那里,我输入了运行控制台应用程序的计算机的 IP(2 台不同的计算机)。如果是外部程序的配置,那应该是全部。

现在关于我的控制台应用程序:

出于测试目的,该应用程序仅在控制台中写入接收到的 json 的时间戳,并且一切都运行良好,直到在某些时候控制台不显示新条目,尽管在发送程序中我可以看到创建了新状态。我已经监视了与 Wireshark 的连接,一切似乎都很正常,预计在命名问题 Wireshark 显示没有更多流量之后。如果我重新启动其中一个应用程序而另一个仍在运行,然后再次启动另一个应用程序,它会再次运行 1-2 分钟。

如果您还有其他需要知道的事情,请告诉我。

private static readonly HttpListener Listener = new HttpListener();

主要的

        // Specified password and username for basic http authentification
        pass.SetValue("LKGsgcxSXh", 0);
        pass.SetValue("r0QNdbqJCdPz3WdpSRqi", 1);

        Listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
        HttpListenerTimeoutManager manager;
        manager = Listener.TimeoutManager;
        manager.IdleConnection = TimeSpan.FromSeconds(2);


        Listener.Prefixes.Add("https://+:443/api/");
        Listener.Start();
        Listen();
        Console.WriteLine("Listening...");
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

私有静态异步无效听()

        while (true)
        {
            var context = await Listener.GetContextAsync();
            Console.WriteLine("Client connected");
            await Task.Factory.StartNew(() => ProcessRequest(context));
        }

        Listener.Close();

私有静态无效 ProcessRequest(HttpListenerContext 上下文)

        HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
        HttpListenerRequest request = context.Request;

        if (identity.Name == pass[0] && identity.Password == pass[1])
        {

            // Get a stream object for reading and writing
            using (Stream stream = request.InputStream)
            {
                Encoding encoding = request.ContentEncoding;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                 ´// Processing the json and write the timestamp
                }
            }
        }
        else
        {
            Console.WriteLine("Unauthorized access");
        }

标签: c#.nethttpstcplistenerhttplistener

解决方案


推荐阅读