良好的延展性,良好的效能是對Http伺服器的基本要求,我們把上一節中的一個簡單的Http伺服器程式進行擴充,使其具備多執行緒能力.
(1)MutiThreadConnection類
Code
using System;
using System.Net.Sockets;
using System.Threading;
namespace MyHttpSever
{
public class MutiThreadConnection : BaseConnection
{
public MutiThreadConnection(Socket sock):base(sock)
{
}
public void run()
{
Console.WriteLine("當前線程ID是:" + Thread.CurrentThread.ManagedThreadId.ToString());
try
{
string filename = getRequest();
sendResponse(filename);
Console.WriteLine("end one request.");
Console.WriteLine("////////////////////////////");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ConClose();
}
}
}
}
(2)Main方法
Code
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace MyHttpSever
{
class Program
{
static void Main(string[] args)
{
Socket ssock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
IPAddress hostIp = Dns.GetHostEntry("localhost").AddressList[0];
IPEndPoint ep = new IPEndPoint(hostIp, 80);
ssock.Bind(ep); //綁定
Console.WriteLine("開始偵聽.");
//開始偵聽
ssock.Listen(32);
while (true)
{
Socket sock = ssock.Accept(); //等待用戶端請求
MutiThreadConnection client = new MutiThreadConnection(sock);
new Thread(new ThreadStart(client.run)).Start();
}
}
}
}
(3)測試
a.啟動伺服器程式
b.開啟兩個瀏覽器視窗,分別輸入:http:localhost/info.html(確保在你的C:\Inetpub\wwwroot目錄下這樣檔案)
c.伺服器輸出如下:
d.當在第二個瀏覽器視窗輸入地址時,伺服器端輸出如下: