读书笔记-web服务器:TcpListener

 1             // 取得本机Loopback :127.0.0.1
 2             IPAddress address = IPAddress.Loopback;
 3             // 创建访问端点,端口:8081
 4             IPEndPoint endpoint = new IPEndPoint(address,8081);
 5 
 6             // 创建Tcp监听器
 7             TcpListener tcpserver = new TcpListener(endpoint);
 8             // 启动监听
 9             tcpserver.Start();
10             Console.WriteLine("开始监听。。。。。");
11             while (true)
12             {
13                 // 等待客户连接
14                 TcpClient tcpClient = tcpserver.AcceptTcpClient();
15                 Console.WriteLine("已经建立连接。");
16                 // 得到数据量
17                 NetworkStream stream = tcpClient.GetStream();
18 
19                 // 采用UTF-8 编码
20                 Encoding utf8 = Encoding.UTF8;
21 
22                 byte[] request = new byte[4096];
23 
24                 int length = stream.Read(request, 0, 4096);
25 
26                 string requesting = utf8.GetString(request);
27                 Console.WriteLine(requesting);
28 
29                 // 状态行
30                 string statusline = "HTTP/1.1 200 OK\r\n";
31                 byte[] statusBuffer = utf8.GetBytes(statusline);
32 
33                 // 准备发送到客户端的网页
34                 string responsestring = "<html><head><title>标题</title></head><body><h1>内容</h1></body></html>";
35                 byte[] responseBuffer = utf8.GetBytes(responsestring);
36                 // 回应头
37                 string responseHead = string.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", responseBuffer.Length);
38                 byte[] responseHeadBuffer = utf8.GetBytes(responseHead);
39 
40                 // 状态行
41                 stream.Write(statusBuffer, 0, statusBuffer.Length);
42                 // 回应头
43                 stream.Write(responseHeadBuffer, 0, responseHeadBuffer.Length);
44                 // 空行 \r\n
45                 stream.Write(new byte[]{13,10},0,2);
46                 // 内容
47                 stream.Write(responseBuffer, 0, responseBuffer.Length);
48                 tcpClient.Close();
49                 if (Console.KeyAvailable)
50                 {
51                     break;
52                 }
53             }
54             // 停止监听
55             tcpserver.Stop();
posted @ 2012-05-10 13:36  Tom.汤  阅读(537)  评论(1编辑  收藏  举报