HttpListener 实现web服务器

用于小型服务器,简单、方便、不需要部署。

总共代码量不超过50行。

 static void Main(string[] args)
{
//创建HTTP监听
using (var httpListener = new HttpListener())
{
//监听的路径
httpListener.Prefixes.Add("http://localhost:8820/");
//设置匿名访问
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
//开始监听
httpListener.Start();
Console.WriteLine("监听端口:8820...");
while (true)
{
//等待传入的请求接受到请求时返回,它将阻塞线程,直到请求到达
var context = httpListener.GetContext();
//取得请求的对象
HttpListenerRequest request = context.Request;
Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
var reader = new StreamReader(request.InputStream);
var msg = reader.ReadToEnd();//读取传过来的信息 //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; // 设置回应头部内容,长度,编码
response.ContentEncoding = Encoding.UTF8;
//response.ContentType = "text/plain;charset=utf-8"; //var path = @"C:\Users\wyl\Desktop\cese\";
////访问的文件名
//var fileName = request.Url.LocalPath; //读取文件内容
//var buff = File.ReadAllBytes(path + fileName);
//response.ContentLength64 = buff.Length; //-------------------------
//byte[] data = new byte[1] { 1 };
//StringWriter sw = new StringWriter();
//XmlSerializer xm = new XmlSerializer(data.GetType());
//xm.Serialize(sw, data);
//var buff = Encoding.UTF8.GetBytes(sw.ToString());
//------------------------ //-------------------------------
//构造soap请求信息
//response.ContentType = "text/xml; charset=utf-8";
//StringBuilder soap = new StringBuilder();
//soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
//soap.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
//soap.Append("<soap:Body>");
//soap.Append("<GetIPCountryAndLocal xmlns=\"http://tempuri.org/\">");
//soap.Append("<RequestIP>183.39.119.90</RequestIP>");
//soap.Append("</GetIPCountryAndLocal>");
//soap.Append("</soap:Body>");
//soap.Append("</soap:Envelope>");
//byte[] buff = Encoding.UTF8.GetBytes(soap.ToString());
//----------------------------------- response.ContentType = "text/xml; charset=utf-8";
string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
byte[] buff = Encoding.UTF8.GetBytes(responseString); // 输出回应内容
System.IO.Stream output = response.OutputStream;
output.Write(buff, , buff.Length);
// 必须关闭输出流
output.Close();
}
}
}

可通过网页直接访问。

程序访问方法

string httpUrl = System.Configuration.ConfigurationManager.AppSettings["url"];// http://localhost:8820/
WebRequest webRequest = WebRequest.Create(httpUrl);
webRequest.ContentType = "text/xml; charset=utf-8";
webRequest.Method = "POST";
string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
using (Stream requestStream = webRequest.GetRequestStream())
{
byte[] paramBytes = Encoding.UTF8.GetBytes(responseString);
requestStream.Write(paramBytes, , paramBytes.Length);
} //响应
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string result = "";
result = myStreamReader.ReadToEnd();
}

JSON数据传输方法

//data未数据对象
string str = JsonConvert.SerializeObject(data);
string res = Post(httpUrl, str); public static string Post(string url, string json)
{
string st;
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = ;
request.ContentType = "application/json";
//request.ContentType = "text/xml; charset=utf-8";
byte[] jsonbyte = Encoding.UTF8.GetBytes(json);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
st = sr.ReadToEnd();
}
catch (WebException ex)
{
//Log4netHelper.WriteErrorLog(url, ex);
st = null;
} return st;
}

HttpListener 实现小型web服务器的更多相关文章

  1. C语言构建小型Web服务器

    #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <string ...

  2. MINI_httpd移植,构建小型WEB服务器

    一.简介 目的:构建小型WEB站,具备SSL. mini_httpd is a small HTTP server. Its performance is not great, but for low ...

  3. Tiny server:小型Web服务器

    一.背景 csapp的网络编程粗略的介绍了关于网络编程的一些知识,在最后的一节主要就实现了一个小型的Webserver.这个server名叫Tiny,它是一个小型的可是功能齐全的Webserver.在 ...

  4. 小型web服务器thttpd的学习总结(上)

    1.软件的主要架构 软件的文件布局比较清晰,主要分为6个模块,主模块是thttpd.c文件,这个文件中包含了web server的主要逻辑,并调用了其他模块的函数.其他的5个模块都是单一的功能模块,之 ...

  5. 小型web服务器thttpd的学习总结(下)

    1.主函数模块分析 对于主函数而言,概括来说主要做了三点内容,也就是初始化系统,进行系统大循环,退出系统.下面主要简单阐述下在这三个部分,又做了哪些工作呢. 初始化系统 拿出程序的名字(argv[0] ...

  6. WPF 使用HttpListener搭建本地web服务器

    准备工作 using Micro.Listener 类(Micro.Listener.dll)下载 调用示例:一.启动服务:new Micro.Listener.ListenerSync(8080). ...

  7. atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty  HttpListener

    atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty  HttpListener 1. 自定义web服务器的实现方案,基于原始socket vs   ...

  8. Raspkate - 基于.NET的可运行于树莓派的轻量型Web服务器

    最近在业余时间玩玩树莓派,刚开始的时候在树莓派里写一些基于wiringPi库的C语言程序来控制树莓派的GPIO引脚,从而控制LED发光二极管的闪烁,后来觉得,是不是可以使用HTML5+jQuery等流 ...

  9. 前端学HTTP之WEB服务器

    前面的话 Web服务器每天会分发出数以亿计的Web页面,它是万维网的骨干.本文主要介绍WEB服务器的相关内容 总括 Web服务器会对HTTP请求进行处理并提供响应.术语“Web服务器”可以用来表示We ...

随机推荐

  1. abp实战-ContosoUniversity Abp版-1运行项目

    1. 去abp官网下载模板工程,当前最新版本是abp5.0,基于.net core 3.0 https://aspnetboilerplate.com/ 项目名称为ContosoAbp 这里使用的是n ...

  2. 使用dapper遇到的问题及解决方法

    在使用dapper进行数据查询时遇到的一个问题,今天进行问题重现做一个记录,免得忘记以后又犯同样的错误. 自己要实现的是:select * from tablename where id in(1,2 ...

  3. python数据可视化简介(一)

    目录 一:配置jupyter notebook 二:Matplotlib图像实例   数据可视化是用图形或者表格的形式进行数据显示,用图形化的手段,清晰有效地传递与沟通信息.既要保证直观易分析,又要保 ...

  4. MySQL入门——在Linux下安装和卸载MySQL

    MySQL入门——在Linux下安装和卸载MySQL 摘要:本文主要学习了如何在Linux系统中安装和卸载MySQL数据库. 查看有没有安装过MySQL 使用命令查看有没有安装过: [root@loc ...

  5. Ubuntu的系统应用

    1:最近在苹果笔记本做了双系统,启动电脑后还是蛮酷的,但是ubuntu系统安好后,没有wifi图标,于是必须连接有线网络,更新数据包才可以. 2:      常用命令 查看软件xxx安装内容#dpkg ...

  6. H5 移动端 键盘遮挡焦点元素解决方案

    前言 最近在做 webapp,遇到了很多移动端兼容的问题,其中一个问题就是:输入框触发 focus 后,键盘弹出,然后遮住了输入框. 然后在Android和IOS上,这个问题的表现形式不一样,而原生键 ...

  7. uni-app条件编译:#ifdef #ifndef #endif

    语法: // #ifdef %PLATFORM% 这些代码只在该平台编译 // #endif #ifdef :      if defined  仅在某个平台编译 #ifndef :     if n ...

  8. ES2019新特性的学习

    前言 前端技术更新的实在是太快了,各种框架百花齐放,随着NodeJs不断的兴起,各种构建工具也是层出不穷,这不,前两周尤雨溪开源了Vue.js3.0源码之后,很多大佬早已把源码剖析皮都不剩了:昨天No ...

  9. NSURLSession中的downloadTask的使用

    1.用downloadTask下载图片 优点:简单 缺点:不能监听下载的进度 代码示例: NSURL *url = [NSURL URLWithString:@"http://pic1.wi ...

  10. MySQL数据篇(五)--SQL对数据进行按月统计,或对数据进行按星期统计

    对于所有的需求,当你不知道怎么处理的时候,你就先用最简单的方法,或者说的明白一点,用最原始的方法,先实现业务需求再说. 一.对提现队列数据表“ims_checkout_task”进行汇总统计,按月汇总 ...