摘自《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();
}
}
}