关于HTTP协议的具体内容,前面章节已经有所讲解,相信读者已有所了解,在此不在累述,本章节讲解自定义web服务器。

 一,.net提供自定义Web服务器的类

以下只是写主要的类

1.HTTPListener:对TCPListener的封装

2.TCPListener:对Socket的封装

3.Socket:对协议栈传输层接口的封装

 二,用.net提供的类进行web服务器的自定义

1.用HTTPListener

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Globalization;
using System.Threading; namespace Microsoft.Samples.HttpListener
{
static class HttpRequestListener
{
public static void Main()
{
string[] prefixes = new string[];
prefixes[] = "http://localhost:8080/";
ProcessRequests(prefixes);
} private static void ProcessRequests(string[] prefixes)
{
if (!System.Net.HttpListener.IsSupported)
{
Console.WriteLine(
"Windows XP SP2, Server 2003, or higher is required to " +
"use the HttpListener class.");
return;
}
// URI prefixes are required,
if (prefixes == null || prefixes.Length == )
throw new ArgumentException("prefixes"); // Create a listener and add the prefixes.
System.Net.HttpListener listener = new System.Net.HttpListener();
Thread handleRequest = null;
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
} try
{
// 启动监听,开始监听请求
listener.Start();
Console.WriteLine("Listening..."); while(true)
{
HttpListenerResponse response = null; // GetContext 在等待一个请求时将阻塞 .
HttpListenerContext context = listener.GetContext(); handleRequest = new Thread(delegate()
{
try
{
Console.WriteLine("当前线程是否为线程池线程:" + (Thread.CurrentThread.IsThreadPoolThread==true?"是":"否"));
Console.WriteLine("当前线程总数:" + System.Diagnostics.Process.GetCurrentProcess().Threads.Count.ToString());
response = context.Response; string responseBody =
"<HTML><head><script language='javascript' type='text/javascript'>function test(){alert('你好');}</script></head><BODY><form>The time is currently " + DateTime.Now.ToString() + "<br/>";
responseBody += "<input type='button' value='js测试' id='test1' onclick='test();'/><br/><input type='submit' value='提交测试' id='test2' /></form></BODY></HTML>";
string responseHeader =
string.Format(
"Content-Type: text/html; charset=UTf-8;Content-Length: {0}", responseBody.Length); byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody);
response.ContentLength64 = responseBodyBytes.Length;
System.IO.Stream output = response.OutputStream;
// 向客户端发送回应头信息
response.Headers.Add(responseHeader);
// 向客户端发送状态行
response.StatusCode = (int)HttpStatusCode.OK;
response.ProtocolVersion = Version.Parse("1.1");
// 想客户端发送主体部分
output.Write(responseBodyBytes, , responseBodyBytes.Length);
}
catch (HttpListenerException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (response != null)
response.Close();
}
Thread.Sleep();
});
handleRequest.Start();
}
}
catch (HttpListenerException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//停止监听
listener.Close();
Console.WriteLine("Done Listening.");
}
}
}
}

服务端运行效果:

客户端运行效果:

2.用TCPListener

  private static void  ProcessRequestsWithTcpListener()
{
TcpListener server=new TcpListener(IPAddress.Any,); server.Start(); Console.WriteLine("HTTP Server Start Listening...."); while (true)
{
TcpClient client = server.AcceptTcpClient();
Thread handleRequest = new Thread(delegate()
{
try
{
NetworkStream inputoutputstream = client.GetStream();
Byte[] buffer = new Byte[];
int readLength = inputoutputstream.Read(buffer, , buffer.Length);
String inputoutputstring = Encoding.ASCII.GetString(buffer, , readLength); Console.WriteLine("客户端信息:" + client.Client.RemoteEndPoint);
Console.WriteLine("客户端请求信息:\n" + inputoutputstring); String statusLine = "HTTP/1.1 200 OK\r\n";
string responseBody =
"<HTML><head><script language='javascript' type='text/javascript'>function test(){alert('你好');}</script></head><BODY><form>The time is currently " + DateTime.Now.ToString() + "<br/>";
responseBody += "<input type='button' value='js测试' id='test1' onclick='test();'/><br/><input type='submit' value='提交测试' id='test2' /></form></BODY></HTML>";
string responseHeader =
string.Format(
"Content-Type: text/html; charset=UTf-8\r\nContent-Length: {0}\r\n", responseBody.Length + statusLine.Length);
byte[] responseStatusLineBytes = Encoding.UTF8.GetBytes(statusLine);
byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader);
byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody); // 写入状态行信息
inputoutputstream.Write(responseStatusLineBytes, , responseStatusLineBytes.Length);
// 写入回应的头部
inputoutputstream.Write(responseHeaderBytes, , responseHeaderBytes.Length);
// 写入回应头部和内容之间的空行
inputoutputstream.Write(new byte[] { , }, , ); // 写入回应的内容
inputoutputstream.Write(responseBodyBytes, , responseBodyBytes.Length);
}
catch (Exception ex)
{
Console.WriteLine("异常信息:"+ex.Message);
}
finally
{
// 关闭与客户端的连接
client.Close();
} });
handleRequest.Start();
}
}

服务端运行效果:

客户端运行效果:和1类似

3.用Socket

 private static void ProcessRequestsWithSocket()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Any, ));
server.Listen(); Console.WriteLine("HTTP Server Start Listening...."); while (true)
{
Socket client = server.Accept();
Thread handleRequest = new Thread(delegate()
{
try
{
Byte[] buffer = new Byte[];
int readLength = client.Receive(buffer, buffer.Length,SocketFlags.None);
String inputoutputstring = Encoding.ASCII.GetString(buffer, , readLength); Console.WriteLine("客户端信息:" + client.RemoteEndPoint);
Console.WriteLine("客户端请求信息:\n" + inputoutputstring); String statusLine = "HTTP/1.1 200 OK\r\n";
string responseBody =
"<HTML><head><script language='javascript' type='text/javascript'>function test(){alert('你好');}</script></head><BODY><form>The time is currently " + DateTime.Now.ToString() + "<br/>";
responseBody += "<input type='button' value='js测试' id='test1' onclick='test();'/><br/><input type='submit' value='提交测试' id='test2' /></form></BODY></HTML>";
string responseHeader =
string.Format(
"Content-Type: text/html; charset=UTf-8\r\nContent-Length: {0}\r\n", responseBody.Length + statusLine.Length);
byte[] responseStatusLineBytes = Encoding.UTF8.GetBytes(statusLine);
byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader);
byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody); // 写入状态行信息
client.Send(responseStatusLineBytes);
// 写入回应的头部
client.Send(responseHeaderBytes);
// 写入回应头部和内容之间的空行
client.Send(new byte[] { , }); // 写入回应的内容
client.Send(responseBodyBytes);
}
catch (Exception ex)
{
Console.WriteLine("异常信息:" + ex.Message);
}
finally
{
// 关闭与客户端的连接
client.Close();
} });
handleRequest.Start();
}
}

服务端和客户端运行效果和2类似.
    声明:2和3代码修改自:http://www.cnblogs.com/zhili/archive/2012/08/23/WebServer.html 只为交流,不为商用.

备注:面试时,常问的一个问题是:http中post和get请求的区别

个人感觉:1.两者传输方式不同,post将数据放在请求内容里传输,get放在请求行传输

2.post内容没有大小限制,get内容有大小限制。

自定义web服务器(四)的更多相关文章

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

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

  2. 网络知识 - 简易的自定义Web服务器

    简易的自定义Web服务器 基于浏览器向服务端发起请求 两台主机各自的进程之间相互通信,需要协议.IP地址和端口号,IP表示了主机的网络地址,而端口号则表示了主机上的某个进程的地址,IP加Port统称为 ...

  3. [C# 网络编程系列]专题三:自定义Web服务器

    转自:http://www.cnblogs.com/zhili/archive/2012/08/23/2652460.html 前言: 经过前面的专题中对网络层协议和HTTP协议的简单介绍相信大家对网 ...

  4. 转:【专题三】自定义Web服务器

    前言: 经过前面的专题中对网络层协议和HTTP协议的简单介绍相信大家对网络中的协议有了大致的了解的, 本专题将针对HTTP协议定义一个Web服务器,我们平常浏览网页通过在浏览器中输入一个网址就可以看到 ...

  5. 专题三:自定义Web服务器

    前言: 经过前面的专题中对网络层协议和HTTP协议的简单介绍相信大家对网络中的协议有了大致的了解的, 本专题将针对HTTP协议定义一个Web服务器,我们平常浏览网页通过在浏览器中输入一个网址就可以看到 ...

  6. ASP.NET 开发必备知识点(1):如何让Asp.net网站运行在自定义的Web服务器上

    一.前言 大家都知道,在之前,我们Asp.net 的网站都只能部署在IIS上,并且IIS也只存在于Windows上,这样Asp.net开发的网站就难以做到跨平台.由于微软的各项技术的开源,所以微软自然 ...

  7. net网站运行在自定义的Web服务器上

    ASP.NET 开发必备知识点(1):如何让Asp.net网站运行在自定义的Web服务器上   一.前言 大家都知道,在之前,我们Asp.net 的网站都只能部署在IIS上,并且IIS也只存在于Win ...

  8. nginx 隐藏版本号与WEB服务器信息

    nginx不仅可以隐藏版本信息,还支持自定义web服务器信息 先看看最终的隐藏结果吧 具体怎么实现呢,其实也很简单,请往下看 1 官网下载最新稳定版 wget http://nginx.org/dow ...

  9. Visual Studio中用于ASP.NET Web项目的Web服务器

    当您在 Visual Studio 中开发 Web 项目时,需要 Web 服务器才能测试或运行它们. 利用 Visual Studio,您可以使用不同的 Web 服务器进行测试,包括 IIS Expr ...

随机推荐

  1. VS2010 error RC2135: file not found

    VS2010 C++ win32 DLL 工程, 添加 rc 文件, 编辑 String Table. 默认情况下英文版本的 rc 文件能够顺序编译通过,为了让工程支持多语言,将字符串修改为其他语言时 ...

  2. Java 与 Python 的对比

    最近在学习Python, 现在写一个Python程序和Java程序进行对一下比,以此展示各自不同的特点.这个程序的功能是计算([n, m) )之间的闰年.     Python程序如下: def fu ...

  3. OpenJudge / Poj 1928 The Peanuts C++

    链接地址:http://bailian.openjudge.cn/practice/1928 题目: 总时间限制: 1000ms 内存限制: 65536kB 描述 Mr. Robinson and h ...

  4. BootstrapDialog点击空白处禁止关闭

    在乐学一百的项目当中引用到了BootstrapDialog,其中后台发送短信时,为了防止管理员编辑了半天的短息,突然间因为点击某个空白区域导致丢失,所以在此禁用掉点击空白关闭弹出框. 主要属性为: c ...

  5. 在linux CentOS6上安装web环境

    感谢浏览,欢迎交流=.= 都说linux作为服务器优于window,近期也是学习了下linux. win7下安装了linux虚拟机,购买linux阿里云主机,开启linux之旅. 进入正题,在linu ...

  6. java oop

    /** 多层嵌套内部类, 调用时要层层往下调用 格式: 外部类.内部类1.内部类2 对象名 = new 外部类().new 内部类1().new 内部类2(); 对象名.属性/方法名(); */ cl ...

  7. iis7以上版本权限控制

    IIS7.5中(仅win7,win2008 SP2,win2008 R2支持),应用程序池的运行帐号,除了指定为LocalService,LocalSystem,NetWorkService这三种基本 ...

  8. Pascal、VB、C#、Java四种语法对照表

    因为工作原因,自学会了vb后陆续接触了其它语言,在工作中经常需要与各家使用不同语言公司的开发人员做程序对接,初期特别需要一个各种语法的对照比,翻看了网络上已有高人做了整理,自己在他基础上也整理了一下, ...

  9. 总结源码编译安装mysql

    最近在学习源码编译安装LAMP.LNMP时,一直遇到一个难题,就是就是mysql无论怎么源码编译安装,到最后启动服务都提示"Starting MySQL.The server quit wi ...

  10. ORA-12012 error on auto execute of job 8887

    *** ACTION NAME:(AUTO_SPACE_ADVISOR_JOB) -- ::58.046 *** MODULE NAME:(DBMS_SCHEDULER) -- ::58.046 ** ...