TCP socket BeginReceive giving me in-order socket data out of order
I'm communicating with a serial port on a terminal server, so in-order guarantee is important. According to Wireshark the packets are coming in in order. The Sequences are also fine.
But my buffer that I write to with the Async Callback is sometimes, not always, receiving packet data out of order. I thought TCP guaranteed in order reception of data?
In the code below, at the very bottom, it's the InputBuffer that gets the data out of order sometimes. What's going on?
private v开发者_高级运维oid 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;
精彩评论