I have written a very simple web server using the HttpListener class. I works well when I test it using my browser.
The problem is when I pull the network cable and then reconnect it to the board again. I always get the following error when I try to restart the HttpListener, I get the following error:
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10048
#### SocketException ErrorCode = 10048
This looks like the port 80 is still in use, but I have no idea how to free the port, so that I can use it again.
When I don’t make any requests from the browser before I pull the canble, the restart works fine.
The board I use is the Spider II and I have installed the latest firmware and SDK.
This is the code I use:
static void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
server_running = true;
httpThread = new Thread(RunServer);
httpThread.Start();
}
else
{
server_running = false;
}
}
private static void ProcessClientGetRequest(HttpListenerContext context)
{
HttpListenerResponse response = context.Response;
if (response != null)
{
response.StatusCode = (int)HttpStatusCode.OK;
Debug.Print("URL: " + context.Request.RawUrl);
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
response.Close();
}
}
internal static void RunServer()
{
HttpListener listener = new HttpListener("http");
int tries = 50;
bool is_started = false;
while ((tries > 0) && (!is_started))
try
{
listener.Start();
is_started = true;
}
catch
{
tries -= 1;
Thread.Sleep(1000);
}
if (is_started)
{
Mainboard.SetDebugLED(true);
Debug.Print("HTTPListener is up and running");
while (server_running)
{
HttpListenerContext context = null;
try
{
context = listener.GetContext();
if (context != null)
{
HttpListenerRequest request = context.Request;
if (request.HttpMethod.ToUpper() == "GET")
{
ProcessClientGetRequest(context);
}
}
else
{
Debug.Print("Gut null context. Closing Server down");
server_running = false;
}
}
catch
{
Debug.Print("Listener Exception");
}
if (context != null)
{
context.Close();
context = null;
}
}
}
else
{
Debug.Print("Too many retry attemps. Giving up");
}
listener.Stop();
listener.Close();
Mainboard.SetDebugLED(false);
}