简体   繁体   中英

Connection drop in HttpListener in C# Mono

I have a code like this

  public async void Start()
   {
       Logger.Log(Logger.LogLevel.General, "Beginning Listen!");

       HttpListener listener = new HttpListener();
       listener.Prefixes.Add(Statics.Config.IniReadValue("http-server"));
       listener.Start();
       while (true)
       {
           HttpListenerContext client = await listener.GetContextAsync();
           AcceptClient(client);
       }   
   }

   public async void AcceptClient(HttpListenerContext client)
    {
        try
        {
            string sRequest = Helpers.GetRequestBody(client.Request);

            if (sRequest == "")
                return;

            client.Response.ContentType = "application/json";

            //Do a bunch of stuff here

            string s = JsonConvert.SerializeObject(response);
            byte[] byteArray = Encoding.UTF8.GetBytes(s);

            client.Response.ContentLength64 = byteArray.Length;
            client.Response.OutputStream.Write(byteArray, 0, byteArray.Length);

            client.Response.OutputStream.Close();
            client.Response.Close();

        }
        catch (Exception e)
        {
            Logger.Log(Logger.LogLevel.Error, e.ToString());
        }
    }

The code works perfectly fine on Windows using .Net but in my testing on Ubuntu 13.04 the client is dropped. I'm using Mono 3.2.1.

The code is for a RPC server which is connected from a C++ client I cannot change. The client expects the connection to remain open throughout the period and fails with broken pipe on unix and error code 5, eof on Windows when using this server with Mono.

There is no problem on connection but after the first command the client fails. There is no exception raised. Thanks for your help!

EDIT 1: I ripped apart the mono HttpListener and used it in my project directly and now it fails on .Net too. Definitely something's wrong with the code. PS this time it was the newest commit code.

My first question and I solved it myself :D

What I was doing wrong was that I was disposing the Request.InputStream stream myself which shouldn't be done. While .Net had no problems with me doing that Mono decided to check whether the connection could be reused or not and failed as the stream was disposed.

So removed the function disposing the stream and it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM