2009-12-21 66 views
2

正如在下面的簡化代碼中,檢查SendAsync()是否已完成傳輸緩衝區中的所有預期字節是否正確?或者是多餘的?這是用於TCP連接套接字。我特別擔心必須在ProcessSend()內發出第二個子調用SendAsync()。例如,如果我有多個線程使用每個消息的新(彙總)SocketAsyncEventArg將數據傳輸到客戶端,那麼同時發送可能是否可能在部分傳輸的消息之間插入?或者這是通過僅允許在數據發送中使用一個SocketAsyncEventArg來控制對客戶端的訪問的一個很好的理由?檢查SendAsync是否完成發送

private void ProcessSend(SocketAsyncEventArgs e) 
{ 
    // Check that data was sent 
    if ((e.SocketError == SocketError.Success) && (e.BytesTransferred > 0)) 
    { 
     AsyncSendUserToken token = (AsyncSendUserToken)e.UserToken; 

     // Check that all the data was sent 
     int offset = e.Offset + e.BytesTransferred; 
     if (offset < e.Count) 
     { 
      // Call send again to finish the send 
      e.SetBuffer(offset, e.Count - offset); 
      bool _willRaiseEvent = token.Socket.SendAsync(e); 
      if (!_willRaiseEvent) 
       ProcessSend(e); 
     } 
    } 
} 
+0

我也看到了這一點,我也看到了傳輸字節數大於e.Count - e.Offset的情況。我正在重新使用一個SocketAsyncEventArgs作爲send,並調用一個填充緩衝區並從ProcessSend調用SendAsync的方法。我添加了代碼來處理ProcessSend中的當前SocketAsynEventArgs並創建一個新的,並且這已經停止了這個錯誤的發生。 – 2011-02-25 03:59:10

回答

1

我認爲有一些錯誤代碼:

// Check that all the data was sent 
int offset = e.Offset + e.BytesTransferred; 
if (offset < e.Count) 
{ 

e.Count是字節數轉移,它不是一個偏移量的字節數組。

因此,爲了比較蘋果蘋果,你會說:

如果(e.BytesTransfered < e.Count) {}