using GHIElectronics.TinyCLR.Networking.Http;
using System.Net;
using System.Text;
// ... (other using statements and namespace)
public class WebServerExample
{
private static HttpListener _listener;
private static int _clientRequestCount = 0;
public static void StartWebServer()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://+:80/"); // Listen on port 80 for all IP addresses
_listener.Start();
while (true)
{
HttpListenerContext context = _listener.GetContext();
ProcessRequest(context);
}
}
private static void ProcessRequest(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "";
if (request.HttpMethod == "GET")
{
// Serve the HTML form
responseString = @"
<HTML><HEAD><TITLE>TinyCLR Form</TITLE></HEAD>
<BODY>
<h1>Control LED</h1>
<form method=""POST"" action=""/"">
<input type=""checkbox"" name=""ledState"" value=""on""> Turn LED On<br>
<input type=""submit"" value=""Submit"">
</form>
</BODY></HTML>";
}
else if (request.HttpMethod == "POST")
{
// Process form submission
string requestBody = new StreamReader(request.InputStream).ReadToEnd();
if (requestBody.Contains("ledState=on"))
{
// Logic to turn on LED (e.g., control a GPIO pin)
responseString = "<HTML><BODY>LED is ON!</BODY></HTML>";
}
else
{
// Logic to turn off LED
responseString = "<HTML><BODY>LED is OFF!</BODY></HTML>";
}
}
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
I changed the code to the following and it works and I get back the form inputs.
char[] msg = new char[request.InputStream.Length];
new StreamReader(request.InputStream).Read(msg, 0, (int) request.InputStream.Length);
string requestBody = new string(msg);