码迷,mamicode.com
首页 > Web开发 > 详细

一个简单的web服务器

时间:2015-04-01 17:01:58      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

       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

一个简单的web服务器

标签:

原文地址:http://www.cnblogs.com/izhiniao/p/4384182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!