asp.net網站底層socket的ftp通信方式搭建伺服器,揭示伺服器底層的一些工作方式 ...
1.首先初始化socket,包含對端點以及對連接隊列長度的初始化
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.建立迴圈,取出(Accept)從socket監聽到的請求,並初始化response socket,包含對狀態行(statusLineBytes)、返回的頭(responseBodyBytes)、返回的客戶端網頁(responseBodyBytes)的初始化併發送
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 line 12 string statusLine = "HTTP/1.1 200 OK\r\n"; 13 byte[] statusLineBytes = utf8.GetBytes(statusLine); 14 15 //Initial response body 16 string responseBody = "<html><head><title>Socket Server</title></head><body>Test socket server</body></html>"; 17 byte[] responseBodyBytes = utf8.GetBytes(responseBody); 18 19 //Initial responseHeader 20 string responseHeader = string.Format("Content-type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", responseBody.Length); 21 byte[] responseHeaderBytes = utf8.GetBytes(responseHeader); 22 23 client.Send(statusLineBytes); 24 client.Send(responseHeaderBytes); 25 client.Send(new byte[] { 13, 10 }); 26 client.Send(responseBodyBytes); 27 28 client.Close(); 29 if (Console.KeyAvailable) 30 break; 31 } 32 socket.Close();
3、使用瀏覽器向伺服器發請求,通過控制台監視伺服器運行
2017-05-10 21:00:59