码迷,mamicode.com
首页 > 其他好文 > 详细

服务器处理静态文件请求

时间:2015-07-18 18:32:46      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

//读取浏览器发过来的内容
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!