/// <summary> /// Checks packet integrity. /// </summary> /// <param name="data">Packet data.</param> /// <returns>Returns true if packet is ok; false if not or data is null.</returns> private bool CheckPacketIntegrity(byte[] data) { if (data == null || data.Length < 1) { return(false); } if (predefinedClientMsgs != null) { return(true); } int len = PacketLenghts.GetLenght(data[0]); if (len == PacketLenghts.Dynamic) { if (data.Length < 3) { return(false); } len = ByteConverter.BigEndian.ToUInt16(data, 1); } return(data.Length == len); }
private void ProcessMessages(byte[] data, bool fromServer) { byte[] buffer = data; byte[] partBuffer; if (fromServer) { partBuffer = fromServerBuffer; } else { partBuffer = fromClientBuffer; } // Part message if (partBuffer != null) { buffer = new byte[partBuffer.Length + data.Length]; Array.Copy(partBuffer, buffer, partBuffer.Length); Array.Copy(data, 0, buffer, partBuffer.Length, data.Length); partBuffer = null; } int offset = 0; // Separate messages while (offset < buffer.Length) { int msgLen = PacketLenghts.GetLenght(buffer[offset]); if (!fromServer && predefinedClientMsgs != null) { if (clientMsgIndex < predefinedClientMsgs.Length) { msgLen = predefinedClientMsgs[clientMsgIndex]; } else { predefinedClientMsgs = null; } } if (msgLen == 0) { byte[] msg = new byte[data.Length - offset]; Array.Copy(data, offset, msg, 0, data.Length - offset); throw new SocketException("Error in communication. Wrong encryption?", this, msg); } if (msgLen != PacketLenghts.Dynamic) { // Fixed sized packet partBuffer = ReadPacket(buffer, msgLen, ref offset, fromServer); } else { // Variable sized packet if (offset + 3 <= buffer.Length) { msgLen = ByteConverter.BigEndian.ToInt16(buffer, offset + 1); // Now we know size partBuffer = ReadPacket(buffer, msgLen, ref offset, fromServer); } else { // Part message does not contain size int partLen = buffer.Length - offset; partBuffer = new byte[partLen]; Array.Copy(buffer, offset, partBuffer, 0, partLen); offset += partLen; } } clientMsgIndex++; } if (fromServer) { fromServerBuffer = partBuffer; } else { fromClientBuffer = partBuffer; } }