欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

读书笔记-web服务器:TcpListener

程序员文章站 2022-06-25 15:52:20
1             // 取得本机loopback...

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();
 

 

摘自  汤瑞新