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. leaflet-webpack 入门开发系列一初探篇(附源码下载)

    前言 leaflet-webpack 入门开发系列环境知识点了解: node 安装包下载webpack 打包管理工具需要依赖 node 环境,所以 node 安装包必须安装,上面链接是官网下载地址 w ...

  2. Microsoft Office自制安装指南 —Nusen_Liu

    Microsoft Word 2010 正版下载安装步骤 版权来自:Nusen_Liu 1.   解压文件(推荐解压到当前文件夹,大神也可以自定义的)下载地址在第16步 (*^__^*) 2.   解 ...

  3. 1_Swift概况

    Swift 标准库 解决复杂的问题并编写高性能,可读的代码 概况 Swift标准库定义了用于编写Swift程序的基本功能,其中包括 1.如基本数据类型Int,Double以及String 2.共同的数 ...

  4. Linux中IP配置

    一.获取网卡名称 ip a ifconfig(安装net-tools后可用) 二.进入网卡配置文件所在路径 cd /etc/sysconfig/network-scripts/ 三.编辑网卡配置文件 ...

  5. RAID 独立磁盘冗余阵列 - redundant array of independent disks

    RAID:  RAID全称是独立磁盘冗余阵列(Redundant Array of Independent Disks),基本思想是把多个磁盘组合起来,组合一个磁盘阵列组,使得性能大幅提高. RAID ...

  6. 最短时间(几秒内)利用C#往SQLserver数据库一次性插入10万条数据

    用途说明: 公司要求做一个数据导入程序,要求将Excel数据,大批量的导入到数据库中,尽量少的访问数据库,高性能的对数据库进行存储.于是在网上进行查找,发现了一个比较好的解决方案,就是采用SqlBul ...

  7. nfs共享文件系统

    NFS服务简介 NFS 就是 Network FileSystem 的缩写,最早之前是由sun 这家公司所发展出来的. 它最大的功能就是可以透过网络,让不同的机器.不同的操作系统.可以彼此分享个别的档 ...

  8. zip unzip 压缩解压缩命令

    直接上例子: mkdir test1 touch test1/1.txt touch test1/2.txt zip -r test1.zip test1    #-r 参数是包含文件夹下的文件 un ...

  9. CodeForces - 1228D (暴力+思维+乱搞)

    题意 https://vjudge.net/problem/CodeForces-1228D 有一个n个顶点m条边的无向图,在一对顶点中最多有一条边. 设v1,v2是两个不相交的非空子集,当满足以下条 ...

  10. 2019.6.13_MySQL简单命令的使用

    1.show databases; -- 显示当前连接下的数据库 2.use db_name;   -- 使用当前数据库db_name 3.show tables;      -- 显示当前数据库下数 ...