在上一篇博文中介紹的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.
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.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
{
// Sends response:
string strResp = "<HTML><BODY>Content length is missing in Post request</BODY></HTML>";
byte[] messageBody = Encoding.UTF8.GetBytes(strResp);
response.ContentType = "text/html";
response.OutputStream.Write(messageBody, 0, messageBody.Length);
}
}
好了,程式編寫好後,直接部署到開發板上進行運行,串連PC,開啟IE 瀏覽器,輸入http://192.168.0.100/a.txt,效果如下:
本意是如果存在a.txt檔案,則下載a.txt的內容,不過我們在代碼中沒有處理。
下面示範一下POST的使用,在IE瀏覽器中輸入:http://192.168.0.100/Upload.asp
IE顯示的內容如下:
我們隨意選擇一個檔案,然後單擊 【Send File Data To Server】按鈕,則Http Server處理POST請求,並返回,IE此時會新彈出一個頁面,如:
在Http Server 的POST處理常式內,我們可以擷取上傳檔案的內容,這裡我們沒有顯示相關內容,只是顯示了它的大小,如611個位元組。
.NET Micro Framework支援的網路功能還很多,如對WCF的支援,有待我們今後細細研究。
-----------------------------------------------------------------------------------------------------------------------
源碼/文檔:http://www.sky-walker.com.cn/MFRelease/Sample/YFHttpServer.rar
MF論壇:http://space.cnblogs.com/group/MFSoft/
MF開發板:http://item.taobao.com/item.htm?id=7117999726
網路開發板:http://item.taobao.com/item.htm?id=10919470266
QQ群:127465602(已滿) 146524112