2010-04-29 45 views
2

也許只是觀看這部影片:http://screencast.com/t/OWE1OWVkO 正如你看到的,被啓動的連接之間的延遲(通過telnet或Firefox)和我的程序首先得到它的話。〜1秒的TcpListener待定()/ AcceptTcpClient()滯後

下面是用於連接

public IDLServer(System.Net.IPAddress addr,int port) 
    { 
     Listener = new TcpListener(addr, port); 

     Listener.Server.NoDelay = true;//I added this just for testing, it has no impact 

     Listener.Start(); 

     ConnectionThread = new Thread(ConnectionListener); 
     ConnectionThread.Start(); 


    } 

    private void ConnectionListener() 
    { 
     while (Running) 
     { 
      while (Listener.Pending() == false) { System.Threading.Thread.Sleep(1); }//this is the part with the lag 
      Console.WriteLine("Client available");//from this point on everything runs perfectly fast 
      TcpClient cl = Listener.AcceptTcpClient(); 

      Thread proct = new Thread(new ParameterizedThreadStart(InstanceHandler)); 
      proct.Start(cl); 


     } 

    } 

等待(我有一些麻煩的代碼放到一個代碼塊)

我已經嘗試了幾個不同的東西,難道是我的代碼使用TcpClient/Listener而不是原始Socket對象?這不是我知道的強制性TCP開銷,並且我嘗試了在同一線程中運行所有內容等。

+0

你最終發現問題了嗎? – vtortola 2014-02-18 11:04:55

+0

好奇你是怎麼解決這個問題的,有同樣的問題 – ruslander 2015-08-05 23:50:52

回答

3

您應該考慮異步接受客戶端,這很可能會消除您看到的延遲。

我修改的代碼略有

public IDLServer(System.Net.IPAddress addr,int port) 
{ 
    Listener = new TcpListener(addr, port); 

    Listener.Start();   

    // Use the BeginXXXX Pattern to accept clients asynchronously 
    listener.BeginAcceptTcpClient(this.OnAcceptConnection, listener); 
} 

private void OnAcceptConnection(IAsyncResult asyn) 
{ 
    // Get the listener that handles the client request. 
    TcpListener listener = (TcpListener) asyn.AsyncState; 

    // Get the newly connected TcpClient 
    TcpClient client = listener.EndAcceptTcpClient(asyn); 

    // Start the client work 
    Thread proct = new Thread(new ParameterizedThreadStart(InstanceHandler)); 
    proct.Start(client); 

    // Issue another connect, only do this if you want to handle multiple clients 
    listener.BeginAcceptTcpClient(this.OnAcceptConnection, listener);  
} 
+2

不行,即使這樣,延遲仍然發生在OnAcceptConnection回調被調用之前。 – cpf 2010-04-29 22:30:30

2

也許這是某種形式的DNS解析的?您是否使用IP地址訪問您的服務器的主機或您的DNS正在解析的某個名稱? ParmesanCodice給出的代碼應該不會延遲,除非客戶端/網絡端出現問題。

嘗試下面的行添加到您的WINDOWS \ SYSTEM32 \ DRIVERS \ ETC \主機:

127.0.0.1  localhost 

它可能解決您的問題或只是連接爲127.0.0.1:85

+1

即使是異步執行,我的連接延遲時間也是1秒。這個答案爲我解決了這個問題,它似乎有點笨,但連接到127.0.0.1而不是本地主機爲我修復它。我的猜測是問題出在一些防火牆/防病毒/安全性問題 – 2013-07-26 06:34:12

0

不會在調試器添加開銷?

我在構建我的MMO服務器時遇到過這樣的問題。 不記得我現在輪到它了。我認爲這與服務的資源分配有關,我使用ParmesanCodice建議的方法(至少是類似的方法),在測試期間,我發現前5到10個連接是垃圾,但之後,服務似乎要甩掉像明日那樣的新連接...

也許它是一個套接字的東西在框架中。

您是否嘗試過負載測試? 拋出1000個連接,看看會發生什麼,處理每個連接後應該會更快。

0

您可以避免整個Listener.Pending while循環。 AcceptTcpClient()是一個阻塞調用,所以你可以讓你的代碼運行並依賴它。我不知道爲什麼這個循環需要1秒(而不是1毫秒),但是因爲你指出這是滯後時間,你可以擺脫它。