• 练习:基于TcpListener的Web服务器。


    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace ConsoleApplication22
    {
        class Program
        {
            static void Main(string[] args)
            {
                IPAddress address = IPAddress.Loopback;
                IPEndPoint endPoint = new IPEndPoint(address, 45678);
                TcpListener newServer = new TcpListener(endPoint);
                newServer.Start();
                Console.WriteLine("Start listening.");
                while (true)
                {
                    TcpClient newClient = newServer.AcceptTcpClient();
                    Console.WriteLine("Connection established.");
                    NetworkStream ns = newClient.GetStream();
                    byte[] request = new byte[4096];
                    int length = ns.Read(request, 0, 4096);
                    string requestString = Encoding.UTF8.GetString(request, 0, 4096);
                    Console.WriteLine(requestString);
    
                    string statusLine = "HTTP/1.1 200 OK\r\n";
                    byte[] statusLineBytes = Encoding.UTF8.GetBytes(statusLine);
                    string responseBody = "<body><head><title>From Jean Server</title></head><body><h1>Hello</h1></body></html>";
                    byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody);
                    string responseHeader = string.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length: {0}\r\n\r\n", responseBody.Length);
                    byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader);
    
                    ns.Write(statusLineBytes, 0, statusLineBytes.Length);
                    ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
                    ns.Write(responseBodyBytes, 0, responseBodyBytes.Length);
                    ns.Close();
                    if (Console.KeyAvailable)
                        break;
                }
                newServer.Stop();
            }
        }
    }
  • 相关阅读:
    vb.net控件数组的问题
    用SQL语句创建和删除Access数据库中的表;添加列和删除列
    vs2003C#datagrid单行行高设定
    三亚自由人攻略.2009最新
    VB.NET窗口渐淡关闭
    都市男女的30声幽默叹息
    Windows 正版增值验证工具如何取消
    VAB删除Word多余空行
    VBA控制菜单栏上的菜单(如页面设置、打印)
    win7 下安装 adams
  • 原文地址:https://www.cnblogs.com/JingG/p/3096332.html
Copyright © 2020-2023  润新知