本文章内容是在上一遍文章更改,主要是请求不同静态文件的内容,如请求1.html或2.html,最后将内容输出到控制台并在浏览器显示出来
//读取浏览器发过来的内容
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);//断开通讯}