Simple Web Server of asp.net Socket, asp. netsocket
1. First initialize the socket, including the initialization of the endpoint and the length of the connection queue
1 IPAddress address = IPAddress.Loopback;2 IPEndPoint endPoint = new IPEndPoint(address, 22222);3 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);4 socket.Bind(endPoint);5 socket.Listen(10);6 Console.WriteLine("Start listening,port:{0}.", endPoint.Port);
2. create a loop, retrieve (Accept) The requests listening from the socket, and initialize the response socket, including the status line (statusLineBytes), response Header (responseBodyBytes), and response client page (responseBodyBytes) initialize and send
1 while (true) 2 { 3 Socket client = socket.Accept(); 4 Console.WriteLine(client.RemoteEndPoint); 5 byte[] buffer = new byte[4096]; 6 int length = client.Receive(buffer, 4096, SocketFlags.None); 7 System.Text.Encoding utf8 = System.Text.UTF8Encoding.UTF8; 8 string requestString = utf8.GetString(buffer, 0, length); 9 Console.WriteLine(requestString);10 11 //Initial status line12 string statusLine = "HTTP/1.1 200 OK\r\n";13 byte[] statusLineBytes = utf8.GetBytes(statusLine);14 15 //Initial response body16 string responseBody = "
3. Send a request to the server using a browser and monitor the server running through the console
21:00:59