zoukankan      html  css  js  c++  java
  • 【ASP.NET】编写自己的Web服务器

      自己写一个简单的Web服务器,对加深理解Http协议有很好的帮助,下面就看一下一个基于TcpListener的Web服务器:

    class Program
        {
            static void Main(string[] args)
            {
                IPAddress address = IPAddress.Loopback;
                IPEndPoint endPoint = new IPEndPoint(address, 49152);
    
                TcpListener newserver = new TcpListener(endPoint);
                newserver.Start();
                Console.WriteLine("开始监听......");
                
                while (true)
                {
                    TcpClient newclient = newserver.AcceptTcpClient();
                    Console.WriteLine("已经建立连接");
    
                    NetworkStream ns = newclient.GetStream();
    
                    System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
    
                    byte[] request=new byte[4096];
                    int lehgth = ns.Read(request, 0, 4096);
                    string requestString = utf8.GetString(request);
    
                    Console.WriteLine(requestString);
    
                    string statusLine = "HTTP/1.1 200 OK
    ";
                    byte[] statusLineBytes = utf8.GetBytes(statusLine);
    
                    string responseBody = "<html><head><body><h1>hello world</h1></body></head></html>";
    
                    byte[] responseBodyBytes = utf8.GetBytes(responseBody);
    
                    //回应头部分
                    string responseHeader = string.Format("Content-Type:text/html;charset=UTF-8
    Content-Length:{0}
    ",responseBody.Length);
    
                    byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);
    
                    ns.Write(statusLineBytes, 0, statusLineBytes.Length);
                    ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
                    ns.Write(new byte[] { 13, 10 }, 0, 2);
                    ns.Write(responseBodyBytes, 0, responseBodyBytes.Length);
                    newclient.Close();
    
                    if (Console.KeyAvailable)
                        break;
                }
                newserver.Stop();
            }


    运行程序,然后打开浏览器,在浏览器窗口中输入服务器的地址:http://localhost:49152,这时就回看到服务器返回的数据。

      

  • 相关阅读:
    java常量池概念【转】
    IntelliJ IDEA 2016 汉化说明:
    intellij idea 添加动态 user library(java.lang.VerifyError)【转】
    IntelliJ IDEA 12 创建Web项目 教程 超详细版【转】
    IntelliJ IDEA 12详细开发教程(一)思想的转变与新手入门【转】
    接口请求时,charles修改请求参数
    monkey测试工具
    操作DOM
    操作表单
    jQuery扩展
  • 原文地址:https://www.cnblogs.com/wywnet/p/3377683.html
Copyright © 2011-2022 走看看