一个简单的web服务器
static void Main(string[] args) { IPAddress localAddress = IPAddress.Loopback;//获取本机的ip地址 IPEndPoint endPoint =new IPEndPoint(localAddress, 49155); Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); socket.Bind(endPoint); socket.Listen(10); while (true) { Console.WriteLine("请求连接等待中 ... "); Socket clientSocket = socket.Accept(); Console.WriteLine("客户端的地址是:{0}",clientSocket.RemoteEndPoint); byte[] buffer = new byte[2048]; int receivelength = clientSocket.Receive(buffer, 2048, SocketFlags.None); string requeststring = Encoding.UTF8.GetString(buffer, 0, receivelength); Console.WriteLine(requeststring); //服务端做出相应的内容 string statusLine = "HTTP/1.1 200 OK\r\n"; byte[] responseStatusLineBytes = Encoding.UTF8.GetBytes(statusLine); string responseBody = "<html><head><title>一个简单的web服务器</title></head><body><p style=‘font:bold;font-size:24pt‘>欢迎你!</p></body></html>"; string responseHeader = string.Format("Content-Type: text/html; charset=UTf-8\r\nContent-Length: {0}\r\n", responseBody.Length); byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody); byte[] responseHeaderBytes = Encoding.UTF8.GetBytes(responseHeader); //向客户端发送状态行 clientSocket.Send(responseStatusLineBytes); //向客户端发送回应头信息 clientSocket.Send(responseHeaderBytes); //发送头部和内容的空行 clientSocket.Send(new byte[] { 13, 10 }); //想客户端发送主体部分 clientSocket.Send(responseBodyBytes); //断开连接 clientSocket.Close(); Console.ReadKey(); break; } //关闭服务器 socket.Close(); }
来源地址 :http://www.cnblogs.com/zhili/archive/2012/08/23/WebServer.html
参考地址 :http://www.cnblogs.com/mcad/p/4343358.html
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。