标签:
//读取浏览器发过来的内容
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));//程序要监听8080端口,如果别的程序已经占了这个端口,那程序就会抛异常
serverSocket.Listen(10);//启动监听10个用户
//进行死循环是为了可以多个请求
while (true)
{
Console.WriteLine("等着请求");
Socket socket = serverSocket.Accept();//等待有人请求,返回上一次Socket的通讯通道
Console.WriteLine("来了请求了");
string firstline;
using (NetworkStream stream = new NetworkStream(socket))
using (StreamReader reader = new StreamReader(stream))
{
firstline = reader.ReadLine();//读取用户访问的页面第一行,读取GET /1.html HTTP/1.1
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
if (line.Length <= 0)
{
break;//遇到空行,请求结束,不用再等了
//如果不break,就一直卡在ReadLine()等着浏览器发出的数据
}
}
}
string[] strs = firstline.Split(‘ ‘);
string url = strs[1];//1.html
//返回给浏览器的内容
using (NetworkStream stream = new NetworkStream(socket))
using (StreamWriter write = new StreamWriter(stream))
{
string filePath = @"D:\1\" + url;
if (File.Exists(filePath))
{
write.WriteLine("HTTP/1.1 200 OK");
write.WriteLine();
string html = File.ReadAllText(filePath);
write.WriteLine(html);
}
else
{
write.WriteLine("HTTP/1.1 404 NOT FOUND");
write.WriteLine();
write.WriteLine("没有找到");
}
}
socket.Disconnect(false);//断开通讯
}
标签:
原文地址:http://www.cnblogs.com/genesis/p/4657259.html