Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. P.S. this time it was the newest commit code.

like image 478
archit Avatar asked May 18 '14 09:05

archit


1 Answers

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!

like image 167
archit Avatar answered Oct 16 '22 08:10

archit