大概的流程如下圖所示:
1 服務端使用HttpListener類 監聽客戶端的連接請求。
HttpListener Listerner = new HttpListener();
服務端新開一個線程,無限循環監聽客戶端的連接請求。
while (true)
{
HttpListenerContext Request= Listerner.GetContext();
ThreadPool.QueueUserWorkItem(ProcessRequest, Request);
}
Listerner.GetContext()函數在沒有連接到來的時候,會掛起當前的線程。
當有連接到來的時候, 利用線程池,把連接請求拋給ProcessRequest函數處理。
private void ProcessRequest(object listenerContext)
{
var context = (HttpListenerContext)listenerContext;
new ClsProcessRequest().Begin(context);
}
ProcessRequest函數新建一個ClsProcessRequest對象,並調用Begin方法對連接請求進行處理。
ClsProcessRequest類獲取客戶端傳過來的url信息。
Begin()函數獲取URL的信息:
this.context = context;
this.context.Response.StatusCode = 200;//設置返回給客服端http狀態代碼
DataLen = Convert.ToInt32(context.Request.ContentLength64);
filename = Path.GetFileName(context.Request.RawUrl);
System.Diagnostics.Debug.WriteLine("原始url:" + context.Request.RawUrl);
System.Diagnostics.Debug.WriteLine("字符總大小:" + DataLen.ToString());
System.Diagnostics.Debug.WriteLine("客戶端的IP:" +context.Request.RemoteEndPoint.ToString());
System.Diagnostics.Debug.WriteLine("上傳的文件名:" + filename);
http上傳下載的請求用以下的函數封裝:
public static string PackMessage(HttpClsMessage MyHttpClsMessage)
{
string All = Start + "|"
+ MyHttpClsMessage.SNNumber +
"|" + MyHttpClsMessage.ComType +
"|" + MyHttpClsMessage.Data +
"|" +MyHttpClsMessage.DownFileName+
"|" +MyHttpClsMessage.UploadFileName
+"|" + End;
return All;
}
Start變量為:S-T-A-R-T
SNNumber:空字符
ComType:UPLOADFILE為上傳圖片,DOWNLOADFILE為下載文件
Data:空
DownFileNmae:請求下載的圖片文件名
UploadFileName:上傳的圖片文件名
End變量:E-N-D
上傳圖片:
原始url:/S-T-A-R-T%7C%7CUPLOADFILE%7C%7C%7C130035953323906250.jpg%7CE-N-D
字符總大小:14736
客戶端的IP:192.168.1.31:1604
上傳的文件名:S-T-A-R-T%7C%7CUPLOADFILE%7C%7C%7C130035953323906250.jpg%7CE-N-D
收到的字符大小:1460
收到的字符大小:8192
收到的字符大小:5084
收到的字符大小:0
發送消息給瀏覽器。
輸入流關閉了。
輸出流關閉了。
從輸出可以看到信息:
是一個上傳圖片的URL請求,%7C也就是字符 ‘| ‘
上傳的圖片文件用匿名方法BeginRead讀取並寫入圖片文件中。
context.Request.InputStream.BeginRead(MyBytes, 0, MyBytes.Length, ReadCallback, null);
using (Stream stream = new FileStream(SecondSubFolder + MyHttpClsMessage.UploadFileName, FileMode.Append, FileAccess.Write))
{
//將字符信息寫入文件系統
stream.Write(MyBytes, 0, ReadSize);
}
下載圖片
原始url:/S-T-A-R-T%7C%7CDOWNFILE%7C%7C7758258.jpg%7C%7CE-N-D
字符總大小:0
客戶端的IP:192.168.1.31:3083
上傳的文件名:S-T-A-R-T%7C%7CDOWNFILE%7C%7C7758258.jpg%7C%7CE-N-D
從輸出可以看到信息:
是一個下載圖片的URL請求,%7C也就是字符 ‘| ‘
using (System.IO.FileStream fs = new FileStream(FullFileName, FileMode.Open, FileAccess.Read))
{
byte[] picbyte = new byte[fs.Length];
using (BinaryReader br = new BinaryReader(fs))
{
picbyte = br.ReadBytes(Convert.ToInt32(fs.Length));
Write(picbyte);
}
}
讀取文件流,發送給客戶端。
-----------------------------------------------------------------------------------------------
演示圖:
源代碼下載:
/Files/gogosai/HttpServerPool.rar
VS2008下編譯通過