I create a thread in my main method that calls WebServer2.Start. There is a Socket called socketGetIP that is used in the main method of my program to get a DHCP when the Netduino boots up. I reuse the socket in the method below to listen for web requests. The issue I am trying to resolve today is the responsiveness of the "server". If I put a breakpoint at EndPoint clientEndPoint = clientSocket.RemoteEndPoint then the page renders everytime. If the breakpoint is disabled then the page may render 1 out of 5 or 1 out of 10 times. Why the inconsistent response ?
EDIT: I noticed my request is null sometimes. Why would this be ? I have a querystring attached to the URI.
public static class WebServer2
{
public static bool blnKeepAlive = true;
//-----------------------------------------------------------------------------------------------------
public static void Start()
{
while (blnKeepAlive==true)
{
try
{
try
{
Program.socketGetIP.Listen(10);
}
catch(Exception ex)
{
Debug.Print(ex.ToString());
}
ListenForRequest();
// Program.socketGetIP.
}
catch (Exception ex)
{
Debug.Print(ex.Message);
Program.blnNetworkUp = false;
Thread.Sleep(30000);
blnKeepAlive = false;
}
}
}
//-----------------------------------------------------------------------------------------------------
private static void ListenForRequest()
{
while (blnKeepAlive == true)
{
try
{
Program.blnWebServerUp = true;
Debug.Print("Web Server Up");
using (Socket clientSocket = Program.socketGetIP.Accept())
{
//Get clients IP
IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
// TODO Use socket available ?
//int byteCount = cSocket.Available;
int bytesReceived = clientSocket.Available;
if (bytesReceived > 0)
{
//Get request
byte[] buffer = new byte[bytesReceived];
int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
string request = new string(Encoding.UTF8.GetChars(buffer));
Debug.Print(request);
//Compose a response
string OperationMessage = ProcessWebRequest(request);
string response = InfoPage(OperationMessage); // Program.currentSystemState.ToString(); // "Hello World";
string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
//Blink the onboard LED
Program.blnWebServerUp = true;
Program.blnNetworkUp = true;
}
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
Program.blnWebServerUp = false;
Program.blnNetworkUp = false; // TODO Do we need this here
Debug.GC(true);
Thread.Sleep(120000);
blnKeepAlive = false;
}
}
}
//-----------------------------------------------------------------------------------------------------