1 // get local Loopback: 127.0.0.1
2 IPAddress address = IPAddress. Loopback;
3 // create an access endpoint, Port: 8081
4 IPEndPoint endpoint = new IPEndPoint (address, 8081 );
5
6 // create a Tcp listener
7 TcpListener tcpserver = new TcpListener (endpoint );
8 // start the listener
9 tcpserver. Start ();
10 Console. WriteLine ("Start listening ..... ");
11 while (true)
12 {
13 // wait for the customer to connect
14 TcpClient tcpClient = tcpserver. AcceptTcpClient ();
15 Console. WriteLine ("A connection has been established. ");
16 // obtain the data volume
17 NetworkStream stream = tcpClient. GetStream ();
18
19 // UTF-8 Encoding
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 // status line
30 string statusline = "HTTP/1.1 200 OK \ r \ n ";
31 byte [] statusBuffer = utf8.GetBytes (statusline );
32
33 // The webpage to be sent to the client
34 string responsestring = "35 byte [] responseBuffer = utf8.GetBytes (responsestring );
36 // Response Header www.2cto.com
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 // status line
41 stream. Write (statusBuffer, 0, statusBuffer. Length );
42 // Response Header
43 stream. Write (responseHeadBuffer, 0, responseHeadBuffer. Length );
44 // empty row \ r \ n
45 stream. Write (new byte );
46 // content
47 stream. Write (responseBuffer, 0, responseBuffer. Length );
48 tcpClient. Close ();
49 if (Console. KeyAvailable)
50 {
51 break;
52}
53}
54 // stop listening
55 tcpserver. Stop ();
From Tang ruixin