Quote:
Originally Posted by KraHen
This would only work if the packet is decrypted already. Also, if ClientReceive is null, you should still handle what`s going on, there`s a small chance you`d miss something with the code you posted above.
Disregarding these, yes, the general idea is correct. In a CO context, you`d decrypt the packet, check if the length is corresponding with the length you received in the packet header, and if not, you know that the next packet is still part of the current one.
|
I am just trying to get the whole idea infront of me so here is an updated version. Is this better/correct ?
Code:
Socket socket = asynchronousState.Socket;
int readLength = socket.EndReceive(ar);
if (sizeof (PacketHeader) <= readLength) {
byte[] bytes = asynchronousState.Buffer.Take(readLength).ToArray();
ushort packetLength = BitConverter.ToUInt16(bytes, 0);
ushort packetType = BitConverter.ToUInt16(bytes, 2);
byte[] packetBody = bytes.Take(bytes.Length - 4).ToArray();
if (packetLength > readLength) {
//Fragmented Packet, receive more.
if (socket.Connected) {
socket.BeginReceive(asynchronousState.Buffer, 0, packetLength, SocketFlags.None, HandleAsyncReceive, asynchronousState);
}
return;
}
if (null != ClientReceive) {
//We have received the whole packet announce it.
ClientReceive(asynchronousState, new Packet
{
Header = new PacketHeader
{
Length = packetLength,
Type = packetType
},
Body = packetBody
});
}
Array.Clear(asynchronousState.Buffer, 0, asynchronousState.Buffer.Length); //Clear for new packet receiving.
if (socket.Connected) {
socket.BeginReceive(asynchronousState.Buffer, 0, asynchronousState.Buffer.Length, SocketFlags.None, HandleAsyncReceive, asynchronousState);
return;
}
}
DisposeSocket(asynchronousState); //Some condition didn't met so disconnect.
Do i need to set the receive index to the last write one or the next receive will receive both the old bytes as well as the new ones ?
socket.BeginReceive(asynchronousState.Buffer, 0, packetLength, SocketFlags.None, HandleAsyncReceive, asynchronousState) ?