c# - 尝试在不存在的网络连接上进行操作,错误代码 1229

标签 c# html

正在处理一个漂亮而简单的 HttpListener,突然弹出这个异常。

An operation was attempted on a nonexistent network connection.

寻找解决方案的时间,但找不到。当我从网页向 HttpListener 提交数据时,代码立即崩溃。 有人可以向我解释如何解决这个问题吗?

代码如下:

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>

最佳答案

本质上,您的问题被触发是因为您在完成请求流的处理之前正在写入响应流。如果您重新排序您的代码以处理请求,那么在您开始尝试编写响应之前,它将起作用。您可能需要重新访问代码,但基本上将其更改为这样会让您继续:

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 */

关于c# - 尝试在不存在的网络连接上进行操作,错误代码 1229,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30706400/

相关文章:

c# - 谁最后决定什么是通用类型?

c# - 在设计 View 中使用 ASP.NET 时,Visual Studio 2012 SP3 更改链接 href

html - 展开滚动条下方的 html 文档

javascript - 将字符串值与用户输入进行比较

c# - MEF 自定义属性类是否需要 ctor(IDictionary<,>)

c# - 找不到类型或命名空间 "SafeIntDictionary"

c# - 如何在循环中获取多个文本框的值

javascript - 比较用户输入的日期值 "instantly"

html - 如何修复按钮左侧的标题

html - 弹出 Div 中的文本在移动设备上消失