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 ...
随机推荐
- 用Python进行数据清洗,这7种方法你一定要掌握
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者 | 常国珍.赵仁乾.张秋剑 来源 |<Python数据科学:技术 ...
- Linux网络——配置网络之iproute家族命令
Linux网络——配置网络之iproute家族命令 摘要:本文主要学习了iproute家族用来配置网络的命令. ip命令 ip命令用于查看和管理IP地址.接口.路由.隧道等.用来取代ifconfig命 ...
- jqgrid后台处理搜索
jqgrid后台处理搜索, 如果点击jqgrid自带的搜索,则向后台传递“_search”参数,和searchField.searchOper.searchString三个值.如下所示: string ...
- Android Studio当中的创建新方法的快捷键该如何使用?
当有红线出现的时候,我们的代码并没有编译出错,则需要输入alt+enter则可以得到相应的神奇效果了.这个方法我竟然今天才知道,也真是丢脸了.比如说我们书写了一个新的没有创建的方法,我们直接输入alt ...
- WindowServer优化
Windows Server 2016 禁止自动更新 1. 打开cmd,输入sconfig,出现如下图: 2. 输入5回车,在输入m回车,完成关闭自动更新.
- 多线程CGD调度组原理
我们常用的GCD调度组方式 //GCD常用调度组写法 -(void)demo1{ //创建调度组和队列 dispatch_group_t group = dispatch_group_create() ...
- Xamarin.Forms iOS 真机测试 打包
等着打包过程中记录一下如何打一个debug包到真机上测试的流程1. 需要在XCode中创建一个新的项目,选择iOS==>Single View App,点击Next 2. 在新的弹框中需要App ...
- [转]国内阿里Maven仓库镜像Maven配置文件Maven仓库速度快
原文地址:http://www.cnblogs.com/ae6623/p/4416256.html 国内连接maven官方的仓库更新依赖库,网速一般很慢,收集一些国内快速的maven仓库镜像以备用. ...
- CentOS 7 Apache 绑定域名和网站
CentOS 7 Apache 绑定域名和网站适用场景一台服务器,运行有多个网站,每个网站都希望用户直接通过二级域名来访问,而不是同一个域名通过子目录来访问 配置过程确定自己的 Apache 服务器的 ...
- eclipse C++ 配置自动提示
转:http://www.cnblogs.com/myitm/archive/2010/12/17/1909194.html 定位到:Windows→Preferences→Java→Editor→C ...