运行效果
客户端
服务端
代码
using System;
using System.Net;
using System.IO;
namespace web简单服务端
{
class Program
{
static void Main(string[] args)
{
using (HttpListener listerner = new HttpListener())
{
listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
listerner.Prefixes.Add("http://localhost:8080/web/");
// listerner.Prefixes.Add("http://localhost/web/");
listerner.Start();
Console.WriteLine("http服务启动");
Console.WriteLine("访问地址:http://localhost:8080/web/?name=您需要输入的参数");
while (true)
{
//等待请求连接
//没有请求则GetContext处于阻塞状态
HttpListenerContext ctx = listerner.GetContext();
ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
string name = ctx.Request.QueryString["name"];
if (name != null)
{
Console.WriteLine(name);
}
NewMethod(ctx, name);
}
listerner.Stop();
}
}
private static void NewMethod(HttpListenerContext ctx, string name)
{
//使用Writer输出http响应代码
using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
{
Console.WriteLine("hello");
writer.WriteLine("<html><head><title>The WebServer Test</title></head><body>");
writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello {0}</p></div>", name);
writer.WriteLine("</body></html>");
writer.Close();
ctx.Response.Close();
}
}
}
}