C#模拟web服务器

今天查了下System.Net. HttpListener类,发现这个可以做一个简易的模拟服务器,与hosts文件一起使用,可以拦截或处理其他向外的请求,如某个软件需要联网检查软件版权。把源码粘上,方便以后使用。

C#模拟web服务器 - 机遇号 - 博客频道 - youkuaiyun.com
http://blog.youkuaiyun.com/hzaccp3/article/details/9310547

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. namespace CodeTest {
  8. class Program {
  9. static void Main(string[] args) {
  10. using(HttpListener listerner = new HttpListener()) {
  11. //添加监听地址,可以添加多个
  12. listerner.Prefixes.Add("http://127.0.0.1:8088/web/");
  13. listerner.Prefixes.Add("http://192.168.1.99:8088/web/");
  14. listerner.Start();
  15. Console.WriteLine("web服务器已启动..");
  16. bool isListerner = true;//服务锁
  17. int count = 0;//客户段请求数量
  18. while(isListerner) {
  19. //等待请求连接 没有请求则GetContext处于阻塞状态
  20. HttpListenerContext ctx = listerner.GetContext();
  21. Console.WriteLine("第" + (++count) + "次请求.");
  22. ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
  23. string name = ctx.Request.QueryString["name"];//客户端查询参数
  24. if(name != null) {
  25. Console.WriteLine(name);
  26. }
  27. //使用Writer输出http响应代码
  28. using(StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) {
  29. writer.WriteLine("<html>");
  30. writer.WriteLine(" <head>");
  31. writer.WriteLine(" <meta http-equiv='content-type' content='text/html;charset=utf-8'>");
  32. writer.WriteLine(" <title>c# web服务器</title>");
  33. writer.WriteLine("</head>");
  34. writer.WriteLine("<body>");
  35. writer.WriteLine(" 服务器响应:<br/>");
  36. writer.WriteLine(" 请求信息:<br/>");
  37. //将请求头信息输出
  38. foreach(string header in ctx.Request.Headers.Keys) {
  39. writer.WriteLine(" <b>{0}</b>={1}<br/>",header,ctx.Request.Headers[header]);
  40. }
  41. writer.WriteLine("</body>");
  42. writer.WriteLine("</html>");
  43. writer.Close();//关闭输出流
  44. ctx.Response.Close();
  45. }
  46. }
  47. listerner.Stop();
  48. Console.WriteLine("web服务器已关闭..");
  49. }
  50. }
  51. }
  52. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值