在上一篇博文中介紹的Web Server,其實是Socket程式設計應用,我們這篇文章介紹的是真正的Http Server,支援GET和POST功能。
同樣我們還是在官方示例Http Server上進行修改,為了使示例更清晰,我們盡可能把代碼做的更簡單一些。
主程式直接修改為如下代碼:
public static void Main()
{
try
{
RunServer("http");
}
catch (Exception e)
Debug.Print(e.Message);
}
核心代碼就是對GET和POST請求的支援,這裡我們不要變,代碼如下:
internal static void RunServer(string prefix)
{
HttpListener listener = new HttpListener(prefix, -1);
listener.Start();
while (true)
HttpListenerResponse response = null;
HttpListenerContext context = null;
try
{
context = listener.GetContext();
response = context.Response;
HttpListenerRequest request = context.Request;
switch (request.HttpMethod.ToUpper())
{
case "GET": GetRequest(context); break;
case "POST": PostRequest(context); break;
}
if (response != null)
response.Close();
}
catch
if (context != null)
context.Close();
GET 請求處理代碼如下,我們進行了大幅度的簡化和調整,并且增加了一個upload.asp處理子產品,代碼如下:
private static void GetRequest(HttpListenerContext context)
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string strFilePath = GetPathFromURL(request.RawUrl);
Debug.Print(strFilePath);
response.StatusCode = (int)HttpStatusCode.OK;
// Start HTML document
string strResp = "<HTML><BODY>.Net Micro Framework Example HTTP Server<p>";
// Print requested verb, URL and version.. Adds information from the request.
strResp += "HTTP Method: " + request.HttpMethod + "<br> Requested URL: \"" + request.RawUrl +
"\"<br> HTTP Version: " + request.ProtocolVersion + "\"<p>";
if (strFilePath.ToLower() == "\\upload.asp")
strResp += Resource1.GetString(Resource1.StringResources.PostForm);
else
strResp += "File to access " + strFilePath + "<p>";
strResp += "Directory: \"" + strFilePath + "\" Does not exists";
// Closes HTML
strResp += "</BODY></HTML>";
// Sends it.
byte[] messageBody = Encoding.UTF8.GetBytes(strResp);
response.ContentType = "text/html";
response.OutputStream.Write(messageBody, 0, messageBody.Length);
POST處理部分,我們也進行了簡化,不過變化不大,相關代碼如下:
private static void PostRequest(HttpListenerContext context)
// Retrieves request and response.
// Allocates buffer for reading of message body
byte[] postdata = new byte[BUFFER_SIZE];
// Now reads the posted data. The content length should be supplied.
// It is error not to have content length with post request.
if (request.ContentLength64 > 0)
Debug.Print("Request Headers:");
Debug.Print(request.Headers.ToString());
long totalBytesReceived = 0;
long contLen = request.ContentLength64;
while (totalBytesReceived < contLen)
int bytesToRead = (int)(contLen - totalBytesReceived);
// Limit to buffer size
bytesToRead = bytesToRead < BUFFER_SIZE ? bytesToRead : BUFFER_SIZE;
int dataRead = request.InputStream.Read(postdata, 0, bytesToRead);
if (dataRead == 0)
// Definitely some error. Means file incomplete.
break;
}
totalBytesReceived += dataRead;
};
// Sends response:
string strResp = "<HTML><BODY>.Net Micro Framework Example HTTP Server<p>";
// Print requested verb, URL and version.. Adds information from the request.
strResp += "HTTP Method: " + request.HttpMethod + "<br> Requested URL: \"" + request.RawUrl +
"\"<br> HTTP Version: " + request.ProtocolVersion + "\"<p>";
strResp += "Amount of data received in message body: " + totalBytesReceived + "<br>";
strResp += "Data of message body is discarded (if there is no filesystem). Please review HTTP Server sample code to add processing of data";
strResp += "</BODY></HTML>";
response.StatusCode = (int)HttpStatusCode.OK;
byte[] messageBody = Encoding.UTF8.GetBytes(strResp);
response.ContentType = "text/html";
response.OutputStream.Write(messageBody, 0, messageBody.Length);
else // Content length is missing, send error back
string strResp = "<HTML><BODY>Content length is missing in Post request</BODY></HTML>";
response.OutputStream.Write(messageBody, 0, messageBody.Length);

本意是如果存在a.txt檔案,則下載下傳a.txt的内容,不過我們在代碼中沒有處理。
IE顯示的内容如下:
我們随意選擇一個檔案,然後單擊 【Send File Data To Server】按鈕,則Http Server處理POST請求,并傳回,IE此時會新彈出一個頁面,如下圖:
在Http Server 的POST處理程式内,我們可以擷取上傳檔案的内容,這裡我們沒有顯示相關内容,隻是顯示了它的大小,如611個位元組。
.NET Micro Framework支援的網絡功能還很多,如對WCF的支援,有待我們今後細細研究。
-----------------------------------------------------------------------------------------------------------------------
QQ群:127465602(已滿) 146524112
<a href="http://weibo.com/1804832611?s=6uyXnP"></a>