diff --git a/Assets/Mirror/Runtime/MessagePacker.cs b/Assets/Mirror/Runtime/MessagePacker.cs index 7b2d2d28d..25d858f8d 100644 --- a/Assets/Mirror/Runtime/MessagePacker.cs +++ b/Assets/Mirror/Runtime/MessagePacker.cs @@ -18,6 +18,11 @@ public static class MessagePacker { static readonly ILogger logger = LogFactory.GetLogger(typeof(MessagePacker)); + /// + /// this is the minimum size of a message that mirror will accept + /// + internal const int HeaderSize = sizeof(ushort); + public static int GetId() where T : struct, NetworkMessage { // paul: 16 bits is enough to avoid collisions diff --git a/Assets/Mirror/Runtime/NetworkConnection.cs b/Assets/Mirror/Runtime/NetworkConnection.cs index 1b96db8e6..ac746bfff 100644 --- a/Assets/Mirror/Runtime/NetworkConnection.cs +++ b/Assets/Mirror/Runtime/NetworkConnection.cs @@ -233,9 +233,10 @@ public bool InvokeHandler(T msg, int channelId) /// The data received. internal void TransportReceive(ArraySegment buffer, int channelId) { - if (buffer.Count == 0) + if (buffer.Count < MessagePacker.HeaderSize) { - logger.LogError($"ConnectionRecv {this} Message was empty"); + logger.LogError($"ConnectionRecv {this} Message was too short (messages should start with message id)"); + Disconnect(); return; } diff --git a/Assets/Mirror/Tests/Editor/MessagePackerTest.cs b/Assets/Mirror/Tests/Editor/MessagePackerTest.cs index 701495672..ee5a44cbb 100644 --- a/Assets/Mirror/Tests/Editor/MessagePackerTest.cs +++ b/Assets/Mirror/Tests/Editor/MessagePackerTest.cs @@ -5,6 +5,8 @@ namespace Mirror.Tests [TestFixture] public class MessagePackerTest { + public struct EmptyMessage : NetworkMessage { } + // helper function to pack message into a simple byte[] public static byte[] PackToByteArray(T message) where T : struct, NetworkMessage @@ -113,5 +115,16 @@ public void UnpackInvalidMessage() Assert.That(result2, Is.EqualTo(false)); Assert.That(msgType2, Is.EqualTo(0)); } + + [Test] + public void MessageIdIsCorrectLength() + { + NetworkWriter writer = new NetworkWriter(); + MessagePacker.Pack(new EmptyMessage(), writer); + + ArraySegment segment = writer.ToArraySegment(); + + Assert.That(segment.Count, Is.EqualTo(MessagePacker.HeaderSize), "Empty message should have same size as HeaderSize"); + } } }