1
//HttpListener 只支援win2003及xp哦~
2
using System;
3
using System.Collections.Generic;
4
using System.Text;
5
using System.Net;
6
using System.IO;
7
8
namespace DIOListener
9
...{
10
11
public class HttpServer
12
...{
13
protected HttpListener Listener;
14
protected bool IsStarted = false;
15
16
//使用傳入一個URI String 例如http://127.0.0.1:8080/ 來開始一個我們的HttpServer
17
public void Start(string strUrl)
18
...{
19
if (IsStarted) //已經再Listen就直接Return
20
return;
21
22
if (Listener == null)
23
Listener = new HttpListener();
24
25
//使用傳入的URI String 例如http://127.0.0.1:8080/
26
Listener.Prefixes.Add(strUrl);
27
28
IsStarted = true;
29
Listener.Start(); //開始Listen
30
31
//以非同步方式取得Context
32
IAsyncResult result = this.Listener.BeginGetContext(
33
new AsyncCallback(WebRequestCallback), this.Listener);
34
}
35
36
//停止我們的HttpServer
37
public void Stop()
38
...{
39
if (Listener != null)
40
...{
41
Listener.Close();
42
Listener = null;
43
IsStarted = false;
44
}
45
}
46
47
//有個Web需求進來
48
private void WebRequestCallback(IAsyncResult result)
49
...{
50
//如果Http Server已經停止則不理會
51
if (Listener == null)
52
return;
53
54
//取得Context
55
HttpListenerContext Context = this.Listener.EndGetContext(result);
56
57
//立即開始另一個非同步取得Context
58
Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);
59
60
//處理我們的Web需求
61
ProcessRequest(Context);
62
}
63
64
//處理我們的Web需求
65
private void ProcessRequest(System.Net.HttpListenerContext Context)
66
...{
67
HttpListenerResponse Response = Context.Response;
68
Stream OutputStream = Response.OutputStream;
69
70
//產生回傳的Byte Array
71
byte[] bOutput = System.Text.Encoding.UTF8.GetBytes("<H1>Hello World!!!</H1>");
72
73
//設定ContentType
74
Response.ContentType = "text/html";
75
76
//設定內容長度
77
Response.ContentLength64 = bOutput.Length;
78
79
//寫到Stream中
80
OutputStream.Write(bOutput, 0, bOutput.Length);
81
82
//關閉Stream
83
OutputStream.Close();
84
}
85
}
86
}