share
Stack OverflowAn operation was attempted on a nonexistent network connection, error code 1229
[+13] [2] The_Monster
[2015-06-08 10:11:17]
[ c# html ]
[ https://stackoverflow.com/questions/30706400/an-operation-was-attempted-on-a-nonexistent-network-connection-error-code-1229 ]

Just working on a nice and simple HttpListener and all of the sudden this exception pops-up.

An operation was attempted on a nonexistent network connection.

Look hours for a solution and could not find one. The code crashed as soon as i submit data from the webpage to the HttpListener. Can someone please explain to me how i can fix this issue?

The Code is below:

C#

public static void StartListening()
    {
        
        Stream ouputStream;
        
        
        HttpListener listener = new HttpListener();
        SetPrefixes(listener);
        
        if (listener.Prefixes.Count > 0)
        {
            listener.Start();
           
            Console.WriteLine("HttpClient Started");  

            while(true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request= context.Request;
                HttpListenerResponse response = context.Response;
               
                string html = Properties.Resources.index;
                byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);
                                    
                response.ContentLength64 = webPageBuffer.Length;
                ouputStream = response.OutputStream;
                ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);

                ouputStream.Flush();

                Common.Wait(2000);  
                                 
                String url = request.RawUrl;
                String[] queryStringArray = url.Split('/');
                String postedtext = GetPostedText(request);                   

                byte[] buffer = null;
                
                // Lots of if statements because a switch would not work here.
                if(queryStringArray[0] == "myForm")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved myForm");
                }
                if(queryStringArray[1] == "doSomething")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved doSomething");
                }
                if(buffer != null)
                {
                    response.AddHeader("Cache-Control", "no-cache");
                    response.AddHeader("Acces-Control-Allow-Origin","*");

                    response.ContentLength64 = buffer.Length;
                    ouputStream = response.OutputStream;
                    ouputStream.Write(buffer, 0, buffer.Length);
                    ouputStream.Close();
                }
            }
        }
    }
               
    private static void SetContext(HttpListenerContext context, Stream ouputStream)
    {
        // De GetContext methode blokkeert terwijl die wacht op een aanvraag(request)
        
        
    }

    private static void SetPrefixes(HttpListener listener)
    {
        String[] prefixes = new String[] { "http://localhost:8100/", "http://192.168.33.28:8000/" };

        int i = 0;

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
            i++;
        }
    }


    private static string GetPostedText(HttpListenerRequest request)
    {
        string recievedText;

        using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
        {
            recievedText= reader.ReadToEnd();
        }

        if (recievedText != "")
        {
            Console.WriteLine("{0} RECIEVED: " + recievedText, DateTime.Now);
        }

        return recievedText;
    }

HTML

<html>
    <head> 
        <title>http</title>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <style>

            body{
        font-size: 12px;
        font-family: Arial;
        }

        legend{
            font-weight: bold;
            font-size: 14px !important;
        }


        fieldset{
            width:200px;
            margin: 0;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-right: -50%;
            transform: translate(-50%, -50%) }

        .wrapper{
            width: 100%;
        }

        </style>


        <script language="javascript">

        //<!-- Create variable timer -->
            var timer;


        //<!-- Create Fucntion CheckOne -->
        /* 
            Wannneer de functie aangroepen word, word eerst de timeout van de variable timer geleegd.
            Daarna word er een timeout ingesteld van 2000 (2sec). Die timeout wordt ingeschakeld nadat het textveld niet meer actief beschouwd word(niet meer gebruikt word, de focus blijft wel op het veld.).
            Na die 2 seconden krijgt de volgende textbox de focus met de zelfde manier maar onder een andere functie.
            Zodra hier ook de 2 seconden om zijn verspringt de focus weer maar nu naar een sumbit (verzenden) knop. Dit is gedaan omdat je dan makkelijk op een OK knop kan drukken op het apparaat.
        */

            function CheckOne() {
                 clearTimeout(timer)
                 timer = setTimeout(function(){
                     document.getElementById("two").focus();
                     //clearTimeout(timer);
                 }, 750)
            }

            function CheckTwo(){
                clearTimeout(timer);
                timer = setTimeout(function(){
                     document.getElementById("sub").focus();
                 }, 750)
            }


        </script> 
        



    </head> 

    <body> 

    <div class="wrapper"> 
        <fieldset> 
            <legend>HttpListener </legend><br/> 
            <form id="searchForm" action="http://localhost:8100/myForm/doSomething" >
                Locatienummer: <br />
                <input type="text" id="one" onkeyup="CheckOne()" name="locatienummer"><br />
                Bonnummer: <br />
                <input type="text" id="two" onkeyup="CheckTwo()" name="bonnummer"><br /><br />
                <input id="sub" type="submit" value="Verzenden" />
            </form> 
        </fieldset> 
    </div> 
    <!-- Include the needed files--> 

        <script>
    $("#searchForm").submit(function (event)
    {
        // Stop form from submitting normally
        event.preventDefault();

        // Get some values from elements on the page:
        var $form = $(this),

        locatieValue = $form.find("input[name='locatienummer']").val(),
        bonValue = $form.find("input[name='bonnummer']").val(),

        url = $form.attr("action");

        // Send the data using post
        $.post(url, { a: locatieValue, b: bonValue });

    });
        </script>

    </body> 
</html>
(2) Check for antivirus or firewall block. Also check ,support.microsoft.com/en-us/kb/899268 and stackoverflow.com/questions/7439063/… - Amit
I have checked my firewall and antivirus but i think its something in the code. 1229 has to do with the tcp protcols, i have excecly the same problem - Collin
What line is this exception occuring? - selkathguy
(1) I notice that the ouputStream is not closed. You assign ouputStream twice in the StartListening function, but it gets closed only once, I am not sure whether this solves your problem. But this is something you should consider. - Suresh Kumar Veluswamy
(1) Have you find solution to this? I have a same problem... - Davor
[+13] [2015-07-01 10:38:43] forsvarir

Essentially, your problem is being triggered because you're writing to the response stream, before you complete processing of the request stream. If you reorder your code to process the request, before you start trying to write the response, it will work. You may need to revisit the code, but essentially changing it to this will get you going:

HttpListenerContext context = listener.GetContext();
HttpListenerRequest request= context.Request;
HttpListenerResponse response = context.Response;

// Process Request **First**
String url = request.RawUrl;
String[] queryStringArray = url.Split('/');
String postedtext = GetPostedText(request);                   

// Process Response **Second**
string html = Properties.Resources.index;
byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);

response.ContentLength64 = webPageBuffer.Length;
ouputStream = response.OutputStream;
ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);

ouputStream.Flush();

/* etc */

(2) In my case the problem wasn't order(Probably!). Since my application is limited in resources only one request can be processed at a time. Each processing will take about 10 seconds, if for any reason during this period the client drops connection then we don't have an output response. Is my assumption right? To ensure that I can write to stream I added if(outputStream.CanWrite) to the code, exactly the line before write. - Milad
1
[+1] [2017-07-04 07:47:35] Ge Rong

I got the same exception today and the cause of my case is that I stopped the listener before I tried to write to the HttpResponseStream. The trick is to always write your response first right after getting the listener context.


2