2014-04-10 149 views
0

我實現了一個與this example極其相似的異步客戶端套接字。我有什麼理由不能顯着增加這個緩衝區大小?在這個例子中,緩衝區大小是256字節。在許多的情況下,我的應用程序最終收到的數據是5,000 ++字節的數據。我應該增加緩衝區大小嗎?有沒有什麼原因讓我不應該增加緩衝區大小?異步客戶端套接字,增加緩衝區大小

每過一段時間,我都會遇到一些問題,即數據發生錯誤或缺少塊(尚未確切確認它是哪個)。例如,有一次我收到看起來像這樣

Slice Id="0" layotartX='100' 

一些腐敗的數據稱爲layotartX並不在我的數據中存在的屬性,它應該說佈局= ...而是佈局得到切斷,其他數據會在後面追加。我對字節進行了計數,並注意到它在正好是我的緩衝區大小的256字節處被截斷。很有可能增加我的緩衝區大小可以防止發生這種問題(數據亂序發生?)。無論如何,正如第1段所述,我只是問是否有任何理由,我不應該增加緩衝區大小,如5,000字節甚至10,000字節。

添加一些代碼。下面是我修改的ReceiveCallback函數(請參閱上面關於其餘類的鏈接示例代碼。當ReceiveCallback接收數據時,它會調用我在下面發佈的「ReceiveSomeData」函數。由於某種原因,每隔一段時間「ReceiveSomeData」函數在一個名爲「MyChitterChatter」的類中,「ReceiveCallback」函數在一個名爲「AsyncClient」的類中,所以當你看到ReceiveSomeData函數鎖定「this」時,它鎖定MyChitterChatter類。是有我的問題可以通過說謊?

private static void ReceiveCallback(IAsyncResult ar) 
    { 
     AppDelegate appDel = (AppDelegate)UIApplication.SharedApplication.Delegate; 

     try { 
      // Retrieve the state object and the client socket 
      // from the asynchronous state object. 
      StateObject state = (StateObject) ar.AsyncState; 
      Socket client = state.workSocket; 

      // Read data from the remote device. 
      int bytesRead = client.EndReceive(ar); 

      if (bytesRead > 0) { 
       // There might be more data, so store the data received so far. 
       string stuffWeReceived = Encoding.ASCII.GetString(state.buffer,0,bytesRead); 

       string debugString = "~~~~~ReceiveCallback~~~~~~ " + stuffWeReceived + " len = " + stuffWeReceived.Length + " bytesRead = " + bytesRead; 

       Console.WriteLine(debugString); 


       // Send this data to be received 
       appDel.wallInteractionScreen.ChitterChatter.ReceiveSomeData(stuffWeReceived); 

       // Get the rest of the data. 
       client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, 
        new AsyncCallback(ReceiveCallback), state); 
      } else { 
       // Signal that all bytes have been received. 
       receiveDone.Set(); 
      } 
     } 
     catch (Exception e) { 
      Console.WriteLine("Error in AsyncClient ReceiveCallback: "); 
      Console.WriteLine(e.Message); 
      Console.WriteLine(e.StackTrace); 
     } 
    } 


    public void ReceiveSomeData (string data) 
    { 
     lock(this) 
     { 
      DataList_New.Add(data); 

      // Update the keepalive when we receive ANY data at all 
      IsConnected = true; 
      LastDateTime_KeepAliveReceived = DateTime.Now; 
     } 
    } 

回答

1

是的,你絕對應該增加緩衝區大小的東西更接近你期望在一個讀得到什麼。32K或64K會是大多數用途的不錯選擇話雖如此,如果您使用的是TCP/IP套接字,數據將不會進入「亂序」或「丟失塊」狀態;如果你看到類似的東西,這是你的代碼中的錯誤,而不是套接字中的錯誤。如果您需要幫助,請分享您的代碼。

+0

添加了一些示例代碼。謝謝。 – LampShade

+0

嗨EricLaw,如果你有時間,請你看看我的另一篇文章,關於數據亂序。我能夠更好地重現我的問題。它位於這裏http://stackoverflow.com/questions/23137246/asynchronous-client-socket-receive-buffer-data-out-of-order – LampShade