asp.net Socket的简单Web Server

2018-06-22 07:47:44来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:ASP.NET MVC 提高运行速度的几种性能优化方法

下一篇:NancyFx 2.0的开源框架的使用-ConstraintRouting