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