asp.net Socket的简单Web Server

1.首先初始化socket,包含对端点以及对连接队列长度的初始化

 IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, );
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);
socket.Listen();
Console.WriteLine("Start listening,port:{0}.", endPoint.Port);

2.建立循环,取出(Accept)从socket监听到的请求,并初始化response socket,包含对状态行(statusLineBytes)、返回的头(responseBodyBytes)、返回的客户端网页(responseBodyBytes)的初始化并发送

 while (true)
{
Socket client = socket.Accept();
Console.WriteLine(client.RemoteEndPoint);
byte[] buffer = new byte[];
int length = client.Receive(buffer, , SocketFlags.None);
System.Text.Encoding utf8 = System.Text.UTF8Encoding.UTF8;
string requestString = utf8.GetString(buffer, , length);
Console.WriteLine(requestString); //Initial status line
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine); //Initial response body
string responseBody = "<html><head><title>Socket Server</title></head><body>Test socket server</body></html>";
byte[] responseBodyBytes = utf8.GetBytes(responseBody); //Initial responseHeader
string responseHeader = string.Format("Content-type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", responseBody.Length);
byte[] responseHeaderBytes = utf8.GetBytes(responseHeader); client.Send(statusLineBytes);
client.Send(responseHeaderBytes);
client.Send(new byte[] { , });
client.Send(responseBodyBytes); client.Close();
if (Console.KeyAvailable)
break;
}
socket.Close();

3、使用浏览器向服务器发请求,通过控制台监视服务器运行

asp.net Socket的简单Web Server

asp.net Socket的简单Web Server

2017-05-10 21:00:59

上一篇:认真分析mmap:是什么 为什么 怎么用【转】


下一篇:Ubuntu 18.04 安装Docker