Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Specified network name is no longer available" in Httplistener

I have built a simple web service that simply uses HttpListener to receive and send requests. Occasionally, the service fails with "Specified network name is no longer available". It appears to be thrown when I write to the output buffer of the HttpListenerResponse.

Here is the error:

ListenerCallback() Error: The specified network name is no longer available at System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)

and here is the guilty portion of the code. responseString is the data being sent back to the client:

buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

response.ContentLength64 = buffer.Length;
output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);

It doesn't seem to always be a huge buffer, two examples are 3,816 bytes and, 142,619 bytes, these errors were thrown about 30 seconds apart. I would not think that my single client application would be overloading HTTPlistener; the client does occasionally sent/receive data in bursts, with several exchanges happening one after another.

Mostly Google searches shows that this is a common IT problem where, when there are network problems, this error is shown -- most of the help is directed toward sysadmins diagnosing a problem with an app moreso than developers tracking down a bug. My app has been tested on different machines, networks, etc. and I don't think it's simply a network configuration problem.

What may be the cause of this problem?

like image 694
pc1oad1etter Avatar asked Jan 09 '09 19:01

pc1oad1etter


1 Answers

The problem occurs when you're trying to respond to an invalid request. Take a look at this. I found out that the only way to solve this problem is:

listener = new HttpListener();
listener.IgnoreWriteExceptions = true;

Just set IgnoreWriteExceptions to true after instantiating your listener and the errors are gone.


Update:
For a deeper explanation, Http protocol is based on TCP protocol which works with streams to which each peer writes data. TCP protocol is peer to peer and each peer can close the connection. When the client sends a request to your HttpListener there will be a TCP handshake, then the server will process the data and responds back to the client by writing into the connection's stream. If you try to write into a stream which is already closed by the remote peer the Exception with "Specified network name is no longer available" will occur.

like image 193
Bamdad Avatar answered Sep 25 '22 08:09

Bamdad