一 运行效果
1服务启动
2客户端访问
3服务端相应
4跳转页面
二 代码
using System;
using System.Net;
using System.IO;
namespace http重定向协议实现负载均衡
{
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("WebServer Start Successed.......");
while (true)
{
//等待请求连接
//没有请求则GetContext处于阻塞状态
HttpListenerContext ctx = listerner.GetContext();
ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
ctx.Response.Redirect("https://www.baidu.com");
string name = ctx.Request.QueryString["name"];
if (name != null)
{
Console.WriteLine(name);
}
NewMethod(ctx);
}
listerner.Stop();
}
}
private static void NewMethod(HttpListenerContext ctx)
{
Console.WriteLine("hello");
ctx.Response.Close();
}
}
}