练习:基于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();
        }
    }
}
原文地址:https://www.cnblogs.com/JingG/p/3096332.html