zoukankan      html  css  js  c++  java
  • 练习:基于HttpListener的Web服务器。

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    namespace ConsoleApplication22
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] prefixed = new string[] { "http://localhost:45678/" };
                HttpListener listener = new HttpListener();
                foreach (string s in prefixed)
                {
                    listener.Prefixes.Add(s);
                }
                listener.Start();
                Console.WriteLine("Start listening.");
                while (true)
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
                    Console.WriteLine("Accept: {0}", string.Join(",",request.AcceptTypes));
                    Console.WriteLine("Accept-Language: {0}", string.Join(",", request.UserLanguages));
                    Console.WriteLine("User-Agent: {0}", request.UserAgent);
                    Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
                    Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close");
                    Console.WriteLine("Host: {0}", request.UserHostName);
                    Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
                    HttpListenerResponse response = context.Response;
                    string responseString = string.Format("<html><head><title>From HttpListener Server</title></head><body><h1>Hello, world.</h1><p>{0}</p></body></html>",DateTime.Now.ToString());
                    response.ContentLength64 = Encoding.UTF8.GetByteCount(responseString);
                    response.ContentType =  "Content-Type: text/html;charset=UTF-8";
                    Stream output = response.OutputStream;
                    StreamWriter writer = new StreamWriter(output);
                    writer.Write(responseString);
                    writer.Close();
    
                    if(Console.KeyAvailable)
                        break;
                }
                listener.Stop();
            }
        }
    }
  • 相关阅读:
    HttpClient(4.3.5)
    HttpClient(4.3.5)
    HttpClient(4.3.5)
    Apache Commons 简述
    树形结构在关系数据库中的设计
    JDK Tools
    JDK Tools
    Linux中Shell循环结构for用法笔记
    Linux有关Shell中if用法笔记
    Linux有关Shell中if用法笔记
  • 原文地址:https://www.cnblogs.com/JingG/p/3096776.html
Copyright © 2011-2022 走看看