I'm working on a TCP Server using .NET and the following code is my first attempt to process the received data (from the socket) to create a packet to deliver. Basically, the packet has a header (7 bytes) where the first 3 bytes are always 0x12 0x34 0x89
and the next 7 bytes are the message length. For example:
0x12 0x34 0x89 0x00 0x00 0x00 0x02 0x20 0x20
The packet then is a 2 length packet and the sent data is 0x20 0x20
.
To process this I am using an if-elseif chain, which I don't like. Is there a better pattern to take away that if-elseif chain?
public void ProcessIncomingData(byte[] buffer, int length)
{
for (int i = 0; i < length; i++)
{
ProcessByte(buffer[i]);
}
}
private void ProcessByte(byte b)
{
if (_status == PacketStatus.Empty && b == FirstHeaderByte)
{
_status = PacketStatus.FirstHeaderReceived;
}
else if (_status == PacketStatus.FirstHeaderReceived && b == SecondHeaderByte)
{
_status = PacketStatus.SecondHeaderReceived;
}
else if (_status == PacketStatus.SecondHeaderReceived && b == ThridHeaderByte)
{
_status = PacketStatus.ThirdHeaderReceived;
}
else if (_status == PacketStatus.ThirdHeaderReceived || _status == PacketStatus.ReceivingPacketLenght)
{
const int sizeOfInt32 = sizeof (int);
const int sizeOfByte = sizeof (byte);
_packetLength |= b << (sizeOfInt32 - ++_packetLenghtOffset) * sizeOfByte;
_status = _packetLenghtOffset < 4 ? PacketStatus.ReceivingPacketLenght : PacketStatus.ReceivingData;
}
else if (_status == PacketStatus.ReceivingData)
{
_packet.Add(b);
var receivedByteCount = _packet.Count;
if (receivedByteCount == _packetLength)
{
var packetData = new byte[_packet.Count];
_packet.CopyTo(packetData);
var receivedPacketHandler = PacketReceived;
if(receivedPacketHandler != null)
{
receivedPacketHandler(this, new PacketReceivedEventArgs{ Packet = packetData });
}
ResetControlVariables();
}
}
}
ThridHeaderByte
, and several places you are writingLenght
instead ofLength
. – Lstor Jul 13 '13 at 6:24sizeof
is meant for use inunsafe
code, you shouldn't use it like this. – svick Jul 13 '13 at 9:49