TCP套接字BeginReceive无序地给出了有序套接字数据

时间:2011-04-22 15:47:28

标签: c# .net tcp

我正在与终端服务器上的串口通信,因此有序保证很重要。根据Wireshark的说法,数据包按顺序进入。序列也很好。

但我使用Async Callback写入的缓冲区有时(并非总是)不按顺序接收数据包数据。为了接收数据,我认为TCP有保证吗?

在下面的代码中,最底层的是InputBuffer有时会无序地获取数据。发生了什么事?

private void WaitForData()
{
    try
    {
         if (moCallBack == null)
         {
             moCallBack = new AsyncCallback(OnDataReceived);
         }
         SocketPacket theSocPkt = new SocketPacket();
         theSocPkt.thisSocket = moClientSocket;
         moResult = moClientSocket.BeginReceive(theSocPkt.dataBuffer,
                    0, theSocPkt.dataBuffer.Length,
                    SocketFlags.None,
                    moCallBack,
                    theSocPkt);
}
private void OnDataReceived(IAsyncResult asyn)
{
    try
    {
        //Set up socket data
        SocketPacket socketData = (SocketPacket)asyn.AsyncState;
        int iRx = socketData.thisSocket.EndReceive(asyn);
        if (iRx > 0 && this.modemState.State != MODEM_CONN_STATE.DISCONNECTED)
        {
            byte[] bytes = new byte[iRx];
            bytes = socketData.dataBuffer;
            Array.Resize<byte>(ref bytes, iRx);
            this.HayesBuff.AddRange(bytes);
            modemConnSMachine();
            WaitForData();
        }
    }
}

private void modemConnSMachine()
{
    switch (modemState.State)
    {
        case MODEM_CONN_STATE.CONNECTED:
             switch(chkModResp(this.HayesBuff))
             {
                 case MODEM_RESPONSE.DATA:
                      signConnectionTimeoutTimer.Change(noChatsTimeoutSec, noChatsTimeoutSec);
                      lock (this.InputBuffer)
                      {
                          this.InputBuffer.AddRange(this.HayesBuff);
                          this.HayesBuff.RemoveRange(0, HayesBuff.Count);
                      }
                      break;

0 个答案:

没有答案