基于TcpListerer的web服务器 和 基于HttpListerer的web服务器
摘自《Asp.Net 本质论》作者:郝冠军
/*
为了简化基于TCP协议的监听程序,.NET在System.Net.Sockets命名空间中提供了TcpListerer类,使用它,在构造函数中传递一组网络端点信息就可以准备好监听参数,而不再需要设置使用的网络协议等细节,调用Start方法之后,监听工作开始。AcceptTcpClient方法将阻塞进程,知道一个客户端的连接到达监听器,这个方法将返回一个代表客户端连接的代理对象
*/
class TcpListener_Study
{
public void CreateTcpLister()
{
//获得本机的loopback网络地址,即127.0.0.1
IPAddress address = IPAddress.Loopback;
//创建可以访问的端点,8974 为0表示一个空闲的端口号
IPEndPoint endpoint = new IPEndPoint(address, ); TcpListener newserver = new TcpListener(endpoint);
newserver.Start();
Console.WriteLine("开始监听,端口号:{0}", endpoint.Port);
while (true)
{
//等待客户端连接
TcpClient newclient = newserver.AcceptTcpClient();
Console.WriteLine("已建立连接");
//得到一个网络流
NetworkStream ns = newclient.GetStream(); //准被读取客户端请求的数据,读取的数据放在一个数组中
byte[] request = new byte[]; int lentth = ns.Read(request, , ); string requeststring = Encoding.UTF8.GetString(request, , lentth); Console.WriteLine(requeststring); //回应状态行
string statusLine = "Http/1.1 200 ok \r\n";
byte[] statusLineBytes = Encoding.UTF8.GetBytes(statusLine);
//准备发送到客户端的网页
string responseBody = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"> <title>Socket Study </title></head><body><form id=\"form1\" runat=\"server\"><div>Hello World ,Socket Study </div> </form></body></html>";
byte[] responseBytes = Encoding.UTF8.GetBytes(responseBody);
string responseHeader = string.Format("Content-type:text/html; charset=UTF-8 \r\nContent-length:{0}\r\n", responseBody.Length);
byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader);
//向客户端发送状态信息
ns.Write(statusLineBytes, , statusLineBytes.Length);
//发送回应头
ns.Write(responseHeaderBytes, , statusLineBytes.Length); ns.Write(new byte[] { , },,);
//发送内容
ns.Write(responseBytes, , statusLineBytes.Length);
newclient.Close();
if (Console.KeyAvailable)
{
break;
}
newserver.Stop();
}
}
}
/*
为了进一步简化http协议的监听器,.Net在命名空间System.Net中提供了HttpListener类,伴随这个对象,.NET提供了一系列相关
* 对象封装了HTTP的处理工作。
*
*/
class HttpLisener_Study
{
public void CreateHTTPLister()
{
if (!HttpListener.IsSupported)
{
throw new System.InvalidOperationException("系统必须为xp sp2 server03 以上版本");
}
string[] prefixes = new string[] { "http://localhost:8974/" }; HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{ listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("监听中");
while (true)
{
//阻塞线程,直到请求到达
HttpListenerContext context = listener.GetContext();
Console.WriteLine("已建立连接"); HttpListenerRequest request = context.Request;
Console.WriteLine("{0}{1} http/1.1", request.HttpMethod, request.RawUrl);
Console.WriteLine("Accept:{0}", string.Join(",", request.AcceptTypes));
Console.WriteLine("Accept-language:{0}",string.Join(",",request.UserLanguages)); Console.WriteLine("User-Agent:{0}", string.Join(",", request.UserAgent)); Console.WriteLine("Accept-Encoding:{0}", string.Join(",", 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;
string responseString = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"> <title>Socket Study </title></head><body><form id=\"form1\" runat=\"server\"><div>Hello World ,Socket Study </div> </form></body></html>";
response.ContentLength64 = Encoding.UTF8.GetByteCount(responseString);
response.ContentType = "text/html;charset=UTF-8";
//输出回应内容
System.IO.Stream output = response.OutputStream;
System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
writer.Write(responseString);
writer.Close();
if (Console.KeyAvailable)
{
break;
} listener.Stop();
}
}
}
基于TcpListerer的web服务器 和 基于HttpListerer的web服务器的更多相关文章
- 详解:基于WEB API实现批量文件由一个服务器同步快速传输到其它多个服务器功能
文件同步传输工具比较多,传输的方式也比较多,比如:FTP.共享.HTTP等,我这里要讲的就是基于HTTP协议的WEB API实现批量文件由一个服务器同步快速传输到其它多个服务器这样的一个工具(简称:一 ...
- PHP写的异步高并发服务器,基于libevent
PHP写的异步高并发服务器,基于libevent 博客分类: PHP PHPFPSocketLinuxQQ 本文章于2013年11月修改. swoole已使用C重写作为PHP扩展来运行.项目地址:h ...
- ASP.NET Web Api构建基于REST风格的服务实战系列教程
使用ASP.NET Web Api构建基于REST风格的服务实战系列教程[十]——使用CacheCow和ETag缓存资源 系列导航地址http://www.cnblogs.com/fzrain/p/3 ...
- ASP.NET WEB API构建基于REST风格
使用ASP.NET WEB API构建基于REST风格的服务实战系列教程[开篇] 最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http ...
- web 框架的本质及自定义web框架 模板渲染jinja2 mvc 和 mtv框架 Django框架的下载安装 基于Django实现的一个简单示例
Django基础一之web框架的本质 本节目录 一 web框架的本质及自定义web框架 二 模板渲染JinJa2 三 MVC和MTV框架 四 Django的下载安装 五 基于Django实现的一个简单 ...
- WebApplicationInitializer究 Spring 3.1之无web.xml式 基于代码配置的servlet3.0应用
本文转自http://hitmit1314.iteye.com/blog/1315816 大家应该都已经知道Spring 3.1对无web.xml式基于代码配置的servlet3.0应用.通过spri ...
- Web Service 实例基于Socket创建Web服务
ServerSocket服务器端代码如下: public static void main(String[] args) throws IOException { // 1:建立服务器端的tcp so ...
- Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解
Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解 (本文转自: http://blog.csdn.net/yinhaide/article/details/44756 ...
- 基于gSOAP使用头文件的C语言版web service开发过程例子
基于gSOAP使用头文件的C语言版web service开发过程例子 一服务端 1 打开VS2005,创建一个工程,命名为calcServer. 2 添加一个头文件calc.h,编辑内容如下: 1// ...
- 基于Token的身份认证 与 基于服务器的身份认证
基于Token的身份认证 与 基于服务器的身份认证 基于服务器的身份认证 在讨论基于Token的身份认证是如何工作的以及它的好处之前,我们先来看一下以前我们是怎么做的: HTTP协议是无状态的,也就是 ...
随机推荐
- python学习之re库
正则表达式库re是非常重要的一个库. 首先正则表达式有两种表示类型,一种是raw string类型(原生字符串类型),也就是我们经常看到的r' '的写法,另一种是不带r的写法,称为string类型. ...
- SpringLog4j日志体系实现方式
1.通过web.xml读取log4j配置文件内容 2.通过不同的配置信息,来实现不同的业务输出,注意:log4j可以写入tomcat容器,也可以写入缓存,通过第三方平台读取 #输入规则#log4j.r ...
- _itemmod_add
命令._add items XXX 为目标添加一组物品 `comment` 备注 `categoryId` 组ID `entry` 物品entry `count`数量
- spoj IITWPC4F - Gopu and the Grid Problem 线段树
IITWPC4F - Gopu and the Grid Problem no tags Gopu is interested in the integer co-ordinates of the ...
- python类的成员
一.实例变量:简单的来说就是给对象赋值 class Person: def __init__(self, name, card_no, height, weight, address, laopo): ...
- 小程序模板template
WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用. 定义模板 使用 name 属性,作为模板的名字.然后在<template/>内定义代码片段,如: & ...
- JavaSE习题 第四章 类与对象
问答题: 1.在声明类时,类名应该遵守哪些习惯? 1.与文件名相同2.首字母大写 2.类体内容中有那两类比较重要的成员? 1.成员变量2.方法 3.实例方法可以操作类变量吗?类方法可以操作实例变量吗? ...
- [qt]qstring和string中文支持转换问题
QString str2qstr(const string str) { return QString::fromLocal8Bit(str.data()); } string qstr2str(co ...
- Python中数据类型
一.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序中,整数的表示方法和数学上的写法一模一样,例如:1,100,-8080,0,等等. 计算机由于使用二进制,所以,有时候用 ...
- C++ 实现sqilte创建数据库插入、更新、查询、删除
C/C++ Interface APIs Following are important C/C++ SQLite interface routines, which can suffice your ...