Reading Notes-web server: TcpListener

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.