良好的可伸缩性,良好的性能是对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.当在第二个浏览器窗口输入地址时,服务器端输出如下: