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>
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With