.NET網路編程學習(二) (續)

來源:互聯網
上載者:User

良好的延展性,良好的效能是對Http伺服器的基本要求,我們把上一節中的一個簡單的Http伺服器程式進行擴充,使其具備多執行緒能力.

(1)MutiThreadConnection類

 

Code
using System;
using System.Net.Sockets;
using System.Threading;
namespace MyHttpSever
{
    public class MutiThreadConnection : BaseConnection
    {
        public MutiThreadConnection(Socket sock):base(sock)
        {
        }
        public void run()
        {
            Console.WriteLine("當前線程ID是:" + Thread.CurrentThread.ManagedThreadId.ToString());
            try
            {
                string filename = getRequest();
                sendResponse(filename);
                Console.WriteLine("end one request.");
                Console.WriteLine("////////////////////////////");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                ConClose();
            }
        }
    }
}

 

(2)Main方法

 

Code
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace MyHttpSever
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket ssock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

            IPAddress hostIp = Dns.GetHostEntry("localhost").AddressList[0];
            IPEndPoint ep = new IPEndPoint(hostIp, 80);
            ssock.Bind(ep); //綁定

            Console.WriteLine("開始偵聽.");
            //開始偵聽
            ssock.Listen(32);
            while (true)
            {
                Socket sock = ssock.Accept(); //等待用戶端請求
                MutiThreadConnection client = new MutiThreadConnection(sock);
                new Thread(new ThreadStart(client.run)).Start();
            }
        }
       
    }
}

 

(3)測試
a.啟動伺服器程式

b.開啟兩個瀏覽器視窗,分別輸入:http:localhost/info.html(確保在你的C:\Inetpub\wwwroot目錄下這樣檔案)

 

c.伺服器輸出如下:

d.當在第二個瀏覽器視窗輸入地址時,伺服器端輸出如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.