HttpListener 实现小型web服务器
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服务器的更多相关文章
- C语言构建小型Web服务器
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <string ...
- MINI_httpd移植,构建小型WEB服务器
一.简介 目的:构建小型WEB站,具备SSL. mini_httpd is a small HTTP server. Its performance is not great, but for low ...
- Tiny server:小型Web服务器
一.背景 csapp的网络编程粗略的介绍了关于网络编程的一些知识,在最后的一节主要就实现了一个小型的Webserver.这个server名叫Tiny,它是一个小型的可是功能齐全的Webserver.在 ...
- 小型web服务器thttpd的学习总结(上)
1.软件的主要架构 软件的文件布局比较清晰,主要分为6个模块,主模块是thttpd.c文件,这个文件中包含了web server的主要逻辑,并调用了其他模块的函数.其他的5个模块都是单一的功能模块,之 ...
- 小型web服务器thttpd的学习总结(下)
1.主函数模块分析 对于主函数而言,概括来说主要做了三点内容,也就是初始化系统,进行系统大循环,退出系统.下面主要简单阐述下在这三个部分,又做了哪些工作呢. 初始化系统 拿出程序的名字(argv[0] ...
- WPF 使用HttpListener搭建本地web服务器
准备工作 using Micro.Listener 类(Micro.Listener.dll)下载 调用示例:一.启动服务:new Micro.Listener.ListenerSync(8080). ...
- atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty HttpListener
atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty HttpListener 1. 自定义web服务器的实现方案,基于原始socket vs ...
- Raspkate - 基于.NET的可运行于树莓派的轻量型Web服务器
最近在业余时间玩玩树莓派,刚开始的时候在树莓派里写一些基于wiringPi库的C语言程序来控制树莓派的GPIO引脚,从而控制LED发光二极管的闪烁,后来觉得,是不是可以使用HTML5+jQuery等流 ...
- 前端学HTTP之WEB服务器
前面的话 Web服务器每天会分发出数以亿计的Web页面,它是万维网的骨干.本文主要介绍WEB服务器的相关内容 总括 Web服务器会对HTTP请求进行处理并提供响应.术语“Web服务器”可以用来表示We ...
随机推荐
- Z从壹开始前后端分离【 .NET Core2.2/3.0 +Vue2.0 】框架之七 || API项目整体搭建 6.2 轻量级ORM
本文梯子 本文3.0版本文章 前言 零.今天完成的蓝色部分 0.创建实体模型与数据库 1.实体模型 2.创建数据库 一.在 IRepository 层设计接口 二.在 Repository 层实现相应 ...
- Python中执行系统命令的四种方法
一.os.system方法 在子终端运行系统命令,可以获取命令执行后的返回信息以及执行返回的状态.执行后返回两行结果,第一行是结果, 第二行是执行状态信息,如果命令成功执行,这条语句返回0,否则返回1 ...
- Oracle:Redhat 7.4+Oracle Rac 11.2.0.4 执行root.sh报错处理
一.报错信息 二.原因分析 因为RHEL 7使用systemd而不是initd运行进程和重启进程,而root.sh通过传统的initd运行ohasd进程 三.解决办法 在RHEL 7中ohasd需要被 ...
- Python中使用requests和parsel爬取喜马拉雅电台音频
场景 喜马拉雅电台: https://www.ximalaya.com/ 找到一步小说音频,这里以下面为例 https://www.ximalaya.com/youshengshu/16411402/ ...
- .Net与其他公司接口对接心得
第一次搞这玩意,心里有点紧张,万事开头难,第一次搞过之后,以后就容易了,所以将这次经历记录下来. 这里我们暂且把对接的公司叫A吧,A公司会提供一个接口对接说明,下面是A公司提供的接口说明 请求内容说明 ...
- CSS 2D 转换
通过CSS 2D转换,我们能够对元素进行移动.缩放.转动.拉长或拉伸. 2D转换一共五个属性:transfrom=> translate(X轴数值px,Y轴数值px):元素从其当前位置移动,根据 ...
- 升鲜宝V2.0_生鲜配送行业,对生鲜配送行业的思考及对系统流程开发的反思_升鲜宝生鲜配送系统_15382353715_余东升
升鲜宝V2.0_生鲜配送行业,对生鲜配送行业的思考及对系统流程开发的反思_升鲜宝生鲜配送系统_15382353715_余东升 -----生鲜配送行业现状及存在问题----- 1. 从业者整体素质偏低 ...
- 高并发高可、O2O、微服务架构用学习网站
高并发高可.O2O.微服务架构用学习网站 https://www.itkc8.com 非常感谢http://www.cnblogs.com/skyblog/p/5044486.html 关于架构,笔者 ...
- mySql创建带解释的表及给表和字段加注释的实现代码
1.创建带解释的表 CREATE TABLE test_table( t_id INT(11) PRIMARY KEY AUTO_INCREMENT COMMENT '设置主键自增', t_name ...
- [PHP] PHP调用IMAP协议读取邮件类库
socket.php 为连接socket的类库 imap.php 基于socket的imap协议封装 test.php 进行测试 require_once 'socket.php'; require_ ...