1.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace HttpListen
{
class Program
{
static void Main(string[] args)
{
string[] arr = { "https://localhost:37090/", "https://zhihu.org.cn/a/" };
// SimpleListenerExample(arr);
// test1(arr[1]);
HttpServer httpServer;
//if (args.GetLength(0) > 0)
//{
//httpServer = new MyHttpServer(Convert.ToInt16(args[0]));
httpServer = new MyHttpServer(2345);
//} else {
// httpServer = new MyHttpServer(8080);
//}
Thread thread = new Thread(new ThreadStart(httpServer.listen));
thread.Start();
}
//方法1
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "https://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
Task.Factory.StartNew(() =>
{
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
// listener.Stop();
});
Console.WriteLine("ok");
Console.ReadLine();
}
//方法2
public static void test1(string url)
{
HttpListener httpListener = new HttpListener();
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListener.Prefixes.Add(url);
Console.WriteLine("开始监听··········");
httpListener.Start();
new Thread(new ThreadStart(delegate
{
while (true)
{
HttpListenerContext httpListenerContext = httpListener.GetContext();
httpListenerContext.Response.StatusCode = 200;
using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
{
writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>测试服务器</title></head><body>");
writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello</p></div>");
writer.WriteLine("<ul>");
writer.WriteLine("</ul>");
writer.WriteLine("</body></html>");
}
}
})).Start();
}
}
}
using System;
using System.Colle