From 0fb7bdacff049d5e0a6ee009c660c28a9545ce9a Mon Sep 17 00:00:00 2001 From: vis2k Date: Thu, 30 Jul 2020 23:03:43 +0200 Subject: [PATCH] IMessageBase renamed to NetworkMessage --- .../Authenticators/BasicAuthenticator.cs | 4 +- .../Discovery/NetworkDiscoveryBase.cs | 4 +- .../Components/Discovery/ServerRequest.cs | 2 +- .../Components/Discovery/ServerResponse.cs | 2 +- Assets/Mirror/Editor/Weaver/Weaver.cs | 6 +-- .../Chat/Scripts/ChatNetworkManager.cs | 2 +- Assets/Mirror/Runtime/MessagePacker.cs | 12 ++--- Assets/Mirror/Runtime/Messages.cs | 52 +++++++++++-------- Assets/Mirror/Runtime/NetworkClient.cs | 12 ++--- Assets/Mirror/Runtime/NetworkConnection.cs | 8 +-- Assets/Mirror/Runtime/NetworkDiagnostics.cs | 8 +-- Assets/Mirror/Runtime/NetworkReader.cs | 2 +- Assets/Mirror/Runtime/NetworkServer.cs | 22 ++++---- Assets/Mirror/Runtime/NetworkWriter.cs | 2 +- .../Tests/Editor/ArraySegmentWriterTest.cs | 4 +- Assets/Mirror/Tests/Editor/ArrayWriterTest.cs | 4 +- Assets/Mirror/Tests/Editor/CustomRWTest.cs | 2 +- .../Mirror/Tests/Editor/EnumReadWriteTests.cs | 8 +-- .../Mirror/Tests/Editor/MessageBaseTests.cs | 4 +- .../Editor/ScriptableObjectWriterTest.cs | 2 +- .../Tests/Editor/StructMessagesTests.cs | 2 +- doc/Guides/Communications/NetworkMessages.md | 8 +-- 22 files changed, 89 insertions(+), 83 deletions(-) diff --git a/Assets/Mirror/Authenticators/BasicAuthenticator.cs b/Assets/Mirror/Authenticators/BasicAuthenticator.cs index f8e45c688..43677b1d4 100644 --- a/Assets/Mirror/Authenticators/BasicAuthenticator.cs +++ b/Assets/Mirror/Authenticators/BasicAuthenticator.cs @@ -3,7 +3,7 @@ namespace Mirror.Authenticators { - public struct AuthRequestMessage : IMessageBase + public struct AuthRequestMessage : NetworkMessage { // use whatever credentials make sense for your game // for example, you might want to pass the accessToken if using oauth @@ -15,7 +15,7 @@ public void Serialize(NetworkWriter writer) {} public void Deserialize(NetworkReader reader) {} } - public struct AuthResponseMessage : IMessageBase + public struct AuthResponseMessage : NetworkMessage { public byte code; public string message; diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs index daf4137c1..2de534b15 100644 --- a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs @@ -18,8 +18,8 @@ namespace Mirror.Discovery [DisallowMultipleComponent] [HelpURL("https://mirror-networking.com/docs/Components/NetworkDiscovery.html")] public abstract class NetworkDiscoveryBase : MonoBehaviour - where Request : IMessageBase, new() - where Response : IMessageBase, new() + where Request : NetworkMessage, new() + where Response : NetworkMessage, new() { public static bool SupportedOnThisPlatform { get { return Application.platform != RuntimePlatform.WebGLPlayer; } } diff --git a/Assets/Mirror/Components/Discovery/ServerRequest.cs b/Assets/Mirror/Components/Discovery/ServerRequest.cs index a70a603b2..f224a4bf4 100644 --- a/Assets/Mirror/Components/Discovery/ServerRequest.cs +++ b/Assets/Mirror/Components/Discovery/ServerRequest.cs @@ -1,6 +1,6 @@ namespace Mirror.Discovery { - public struct ServerRequest : IMessageBase + public struct ServerRequest : NetworkMessage { // Weaver will generate serialization public void Serialize(NetworkWriter writer) {} diff --git a/Assets/Mirror/Components/Discovery/ServerResponse.cs b/Assets/Mirror/Components/Discovery/ServerResponse.cs index 0cac4d6a4..a2ac95136 100644 --- a/Assets/Mirror/Components/Discovery/ServerResponse.cs +++ b/Assets/Mirror/Components/Discovery/ServerResponse.cs @@ -3,7 +3,7 @@ namespace Mirror.Discovery { - public struct ServerResponse : IMessageBase + public struct ServerResponse : NetworkMessage { // The server that sent this // this is a property so that it is not serialized, but the diff --git a/Assets/Mirror/Editor/Weaver/Weaver.cs b/Assets/Mirror/Editor/Weaver/Weaver.cs index 8fb3e9986..351825e03 100644 --- a/Assets/Mirror/Editor/Weaver/Weaver.cs +++ b/Assets/Mirror/Editor/Weaver/Weaver.cs @@ -51,7 +51,7 @@ internal static class Weaver public static TypeReference NetworkConnectionType; public static TypeReference MessageBaseType; - public static TypeReference IMessageBaseType; + public static TypeReference NetworkMessageType; public static TypeReference SyncListType; public static TypeReference SyncSetType; public static TypeReference SyncDictionaryType; @@ -299,7 +299,7 @@ static void SetupTargetTypes() NetworkConnectionType = CurrentAssembly.MainModule.ImportReference(NetworkConnectionType); MessageBaseType = NetAssembly.MainModule.GetType("Mirror.MessageBase"); - IMessageBaseType = NetAssembly.MainModule.GetType("Mirror.IMessageBase"); + NetworkMessageType = NetAssembly.MainModule.GetType("Mirror.NetworkMessage"); SyncListType = NetAssembly.MainModule.GetType("Mirror.SyncList`1"); SyncSetType = NetAssembly.MainModule.GetType("Mirror.SyncSet`1"); SyncDictionaryType = NetAssembly.MainModule.GetType("Mirror.SyncDictionary`2"); @@ -404,7 +404,7 @@ static bool WeaveMessage(TypeDefinition td) bool modified = false; - if (td.ImplementsInterface(IMessageBaseType)) + if (td.ImplementsInterface(NetworkMessageType)) { // process this and base classes from parent to child order diff --git a/Assets/Mirror/Examples/Chat/Scripts/ChatNetworkManager.cs b/Assets/Mirror/Examples/Chat/Scripts/ChatNetworkManager.cs index eae046236..6c1357e47 100644 --- a/Assets/Mirror/Examples/Chat/Scripts/ChatNetworkManager.cs +++ b/Assets/Mirror/Examples/Chat/Scripts/ChatNetworkManager.cs @@ -14,7 +14,7 @@ public void SetHostname(string hostname) public ChatWindow chatWindow; - public struct CreatePlayerMessage : IMessageBase + public struct CreatePlayerMessage : NetworkMessage { public string name; diff --git a/Assets/Mirror/Runtime/MessagePacker.cs b/Assets/Mirror/Runtime/MessagePacker.cs index 40ba073fe..09f17ce96 100644 --- a/Assets/Mirror/Runtime/MessagePacker.cs +++ b/Assets/Mirror/Runtime/MessagePacker.cs @@ -19,7 +19,7 @@ public static class MessagePacker { static readonly ILogger logger = LogFactory.GetLogger(typeof(MessagePacker)); - public static int GetId() where T : IMessageBase + public static int GetId() where T : NetworkMessage { // paul: 16 bits is enough to avoid collisions // - keeps the message size small because it gets varinted @@ -35,11 +35,11 @@ public static int GetId(Type type) // pack message before sending // -> NetworkWriter passed as arg so that we can use .ToArraySegment // and do an allocation free send before recycling it. - public static void Pack(T message, NetworkWriter writer) where T : IMessageBase + public static void Pack(T message, NetworkWriter writer) where T : NetworkMessage { // if it is a value type, just use typeof(T) to avoid boxing // this works because value types cannot be derived - // if it is a reference type (for example IMessageBase), + // if it is a reference type (for example NetworkMessage), // ask the message for the real type int msgType = GetId(default(T) != null ? typeof(T) : message.GetType()); writer.WriteUInt16((ushort)msgType); @@ -52,7 +52,7 @@ public static void Pack(T message, NetworkWriter writer) where T : IMessageBa // => useful for tests // => useful for local client message enqueue [EditorBrowsable(EditorBrowsableState.Never)] - public static byte[] Pack(T message) where T : IMessageBase + public static byte[] Pack(T message) where T : NetworkMessage { using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { @@ -64,7 +64,7 @@ public static byte[] Pack(T message) where T : IMessageBase } // unpack a message we received - public static T Unpack(byte[] data) where T : IMessageBase, new() + public static T Unpack(byte[] data) where T : NetworkMessage, new() { using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(data)) { @@ -101,7 +101,7 @@ public static bool UnpackMessage(NetworkReader messageReader, out int msgType) } internal static NetworkMessageDelegate MessageHandler(Action handler, bool requireAuthenication) - where T : IMessageBase, new() + where T : NetworkMessage, new() where C : NetworkConnection => (conn, reader, channelId) => { diff --git a/Assets/Mirror/Runtime/Messages.cs b/Assets/Mirror/Runtime/Messages.cs index 1db614005..d7d69c49e 100644 --- a/Assets/Mirror/Runtime/Messages.cs +++ b/Assets/Mirror/Runtime/Messages.cs @@ -3,15 +3,21 @@ namespace Mirror { - public interface IMessageBase + // NetworkMessages should always be structs to avoid allocations, so we use + // an interface. + // Note: adding empty Serialize/Deserialize function is enough, Weaver will + // do the rest. + public interface NetworkMessage { void Deserialize(NetworkReader reader); - void Serialize(NetworkWriter writer); } - [Obsolete("Please convert your message class to a struct, implement IMessageBase and add empty Serialize/Deserialize methods. Mirror's Weaver will fill them out automatically. Messages should always be structs to avoid runtime allocations, and because we don't want two ways to do the same thing.")] - public abstract class MessageBase : IMessageBase + //[Obsolete("IMessageBase was renamed to NetworkMessage for ease of use.")] + public interface IMessageBase : NetworkMessage {} + + [Obsolete("Please convert your message class to a struct, implement the NetworkMessage interface and add empty Serialize/Deserialize methods. Mirror's Weaver will fill them out automatically. Messages should always be structs to avoid runtime allocations, and because we don't want two ways to do the same thing.")] + public abstract class MessageBase : NetworkMessage { // De-serialize the contents of the reader into this message public virtual void Deserialize(NetworkReader reader) { } @@ -21,7 +27,7 @@ public virtual void Serialize(NetworkWriter writer) { } } #region Public System Messages - public struct ErrorMessage : IMessageBase + public struct ErrorMessage : NetworkMessage { public byte value; @@ -41,21 +47,21 @@ public void Serialize(NetworkWriter writer) } } - public struct ReadyMessage : IMessageBase + public struct ReadyMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct NotReadyMessage : IMessageBase + public struct NotReadyMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct AddPlayerMessage : IMessageBase + public struct AddPlayerMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } @@ -67,28 +73,28 @@ public void Serialize(NetworkWriter writer) { } /// Obsolete: Removed as a security risk. Use NetworkServer.RemovePlayerForConnection instead. /// [Obsolete("Removed as a security risk. Use NetworkServer.RemovePlayerForConnection(NetworkConnection conn, bool keepAuthority = false) instead")] - public struct RemovePlayerMessage : IMessageBase + public struct RemovePlayerMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct DisconnectMessage : IMessageBase + public struct DisconnectMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct ConnectMessage : IMessageBase + public struct ConnectMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct SceneMessage : IMessageBase + public struct SceneMessage : NetworkMessage { public string sceneName; // Normal = 0, LoadAdditive = 1, UnloadAdditive = 2 @@ -120,7 +126,7 @@ public enum SceneOperation : byte #endregion #region System Messages requried for code gen path - public struct CommandMessage : IMessageBase + public struct CommandMessage : NetworkMessage { public uint netId; public int componentIndex; @@ -147,7 +153,7 @@ public void Serialize(NetworkWriter writer) } } - public struct RpcMessage : IMessageBase + public struct RpcMessage : NetworkMessage { public uint netId; public int componentIndex; @@ -174,7 +180,7 @@ public void Serialize(NetworkWriter writer) } } - public struct SyncEventMessage : IMessageBase + public struct SyncEventMessage : NetworkMessage { public uint netId; public int componentIndex; @@ -203,7 +209,7 @@ public void Serialize(NetworkWriter writer) #endregion #region Internal System Messages - public struct SpawnMessage : IMessageBase + public struct SpawnMessage : NetworkMessage { /// /// netId of new or existing object @@ -277,21 +283,21 @@ public void Serialize(NetworkWriter writer) } } - public struct ObjectSpawnStartedMessage : IMessageBase + public struct ObjectSpawnStartedMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct ObjectSpawnFinishedMessage : IMessageBase + public struct ObjectSpawnFinishedMessage : NetworkMessage { public void Deserialize(NetworkReader reader) { } public void Serialize(NetworkWriter writer) { } } - public struct ObjectDestroyMessage : IMessageBase + public struct ObjectDestroyMessage : NetworkMessage { public uint netId; @@ -306,7 +312,7 @@ public void Serialize(NetworkWriter writer) } } - public struct ObjectHideMessage : IMessageBase + public struct ObjectHideMessage : NetworkMessage { public uint netId; @@ -321,7 +327,7 @@ public void Serialize(NetworkWriter writer) } } - public struct UpdateVarsMessage : IMessageBase + public struct UpdateVarsMessage : NetworkMessage { public uint netId; // the serialized component data @@ -343,7 +349,7 @@ public void Serialize(NetworkWriter writer) // A client sends this message to the server // to calculate RTT and synchronize time - public struct NetworkPingMessage : IMessageBase + public struct NetworkPingMessage : NetworkMessage { public double clientTime; @@ -365,7 +371,7 @@ public void Serialize(NetworkWriter writer) // The server responds with this message // The client can use this to calculate RTT and sync time - public struct NetworkPongMessage : IMessageBase + public struct NetworkPongMessage : NetworkMessage { public double clientTime; public double serverTime; diff --git a/Assets/Mirror/Runtime/NetworkClient.cs b/Assets/Mirror/Runtime/NetworkClient.cs index 7ffd904d2..5c286232b 100644 --- a/Assets/Mirror/Runtime/NetworkClient.cs +++ b/Assets/Mirror/Runtime/NetworkClient.cs @@ -238,7 +238,7 @@ static void RemoveTransportHandlers() /// /// /// True if message was sent. - public static bool Send(T message, int channelId = Channels.DefaultReliable) where T : IMessageBase + public static bool Send(T message, int channelId = Channels.DefaultReliable) where T : NetworkMessage { if (connection != null) { @@ -309,7 +309,7 @@ internal static void RegisterSystemHandlers(bool hostMode) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { int msgType = MessagePacker.GetId(); if (handlers.ContainsKey(msgType)) @@ -326,7 +326,7 @@ internal static void RegisterSystemHandlers(bool hostMode) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { RegisterHandler((NetworkConnection _, T value) => { handler(value); }, requireAuthentication); } @@ -338,7 +338,7 @@ internal static void RegisterSystemHandlers(bool hostMode) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { int msgType = MessagePacker.GetId(); handlers[msgType] = MessagePacker.MessageHandler(handler, requireAuthentication); @@ -351,7 +351,7 @@ internal static void RegisterSystemHandlers(bool hostMode) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { ReplaceHandler((NetworkConnection _, T value) => { handler(value); }, requireAuthentication); } @@ -360,7 +360,7 @@ internal static void RegisterSystemHandlers(bool hostMode) /// Unregisters a network message handler. /// /// The message type to unregister. - public static bool UnregisterHandler() where T : IMessageBase + public static bool UnregisterHandler() where T : NetworkMessage { // use int to minimize collisions int msgType = MessagePacker.GetId(); diff --git a/Assets/Mirror/Runtime/NetworkConnection.cs b/Assets/Mirror/Runtime/NetworkConnection.cs index df8d385ac..d268ca559 100644 --- a/Assets/Mirror/Runtime/NetworkConnection.cs +++ b/Assets/Mirror/Runtime/NetworkConnection.cs @@ -94,7 +94,7 @@ public abstract class NetworkConnection : IDisposable /// internal NetworkConnection() { - // set lastTime to current time when creating connection to make sure it isn't instantly kicked for inactivity + // set lastTime to current time when creating connection to make sure it isn't instantly kicked for inactivity lastMessageTime = Time.time; } @@ -146,7 +146,7 @@ internal void SetHandlers(Dictionary handlers) /// The message to send. /// The transport layer channel to send on. /// - public bool Send(T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + public bool Send(T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage { using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { @@ -236,14 +236,14 @@ internal bool InvokeHandler(int msgType, NetworkReader reader, int channelId) /// The message type to unregister. /// The message object to process. /// Returns true if the handler was successfully invoked - public bool InvokeHandler(T msg, int channelId) where T : IMessageBase + public bool InvokeHandler(T msg, int channelId) where T : NetworkMessage { // get writer from pool using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { // if it is a value type, just use typeof(T) to avoid boxing // this works because value types cannot be derived - // if it is a reference type (for example IMessageBase), + // if it is a reference type (for example NetworkMessage), // ask the message for the real type int msgType = MessagePacker.GetId(default(T) != null ? typeof(T) : msg.GetType()); diff --git a/Assets/Mirror/Runtime/NetworkDiagnostics.cs b/Assets/Mirror/Runtime/NetworkDiagnostics.cs index 1a785c902..70743d219 100644 --- a/Assets/Mirror/Runtime/NetworkDiagnostics.cs +++ b/Assets/Mirror/Runtime/NetworkDiagnostics.cs @@ -17,7 +17,7 @@ public readonly struct MessageInfo /// /// The message being sent /// - public readonly IMessageBase message; + public readonly NetworkMessage message; /// /// channel through which the message was sent /// @@ -32,7 +32,7 @@ public readonly struct MessageInfo /// public readonly int count; - internal MessageInfo(IMessageBase message, int channel, int bytes, int count) + internal MessageInfo(NetworkMessage message, int channel, int bytes, int count) { this.message = message; this.channel = channel; @@ -48,7 +48,7 @@ internal MessageInfo(IMessageBase message, int channel, int bytes, int count) /// public static event Action OutMessageEvent; - internal static void OnSend(T message, int channel, int bytes, int count) where T : IMessageBase + internal static void OnSend(T message, int channel, int bytes, int count) where T : NetworkMessage { if (count > 0 && OutMessageEvent != null) { @@ -66,7 +66,7 @@ internal static void OnSend(T message, int channel, int bytes, int count) whe /// public static event Action InMessageEvent; - internal static void OnReceive(T message, int channel, int bytes) where T : IMessageBase + internal static void OnReceive(T message, int channel, int bytes) where T : NetworkMessage { if (InMessageEvent != null) { diff --git a/Assets/Mirror/Runtime/NetworkReader.cs b/Assets/Mirror/Runtime/NetworkReader.cs index 37f901442..93e8d683a 100644 --- a/Assets/Mirror/Runtime/NetworkReader.cs +++ b/Assets/Mirror/Runtime/NetworkReader.cs @@ -374,7 +374,7 @@ public static Uri ReadUri(this NetworkReader reader) return new Uri(reader.ReadString()); } - public static void ReadMessage(this NetworkReader reader, T msg) where T : IMessageBase + public static void ReadMessage(this NetworkReader reader, T msg) where T : NetworkMessage { msg.Deserialize(reader); } diff --git a/Assets/Mirror/Runtime/NetworkServer.cs b/Assets/Mirror/Runtime/NetworkServer.cs index 974aa61e7..5a7a3dcc3 100644 --- a/Assets/Mirror/Runtime/NetworkServer.cs +++ b/Assets/Mirror/Runtime/NetworkServer.cs @@ -253,7 +253,7 @@ public static void ActivateHostScene() // this is like SendToReady - but it doesn't check the ready flag on the connection. // this is used for ObjectDestroy messages. - static void SendToObservers(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + static void SendToObservers(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage { if (logger.LogEnabled()) logger.Log("Server.SendToObservers id:" + typeof(T)); @@ -300,7 +300,7 @@ static void SendToObservers(NetworkIdentity identity, T msg, int channelId = /// Transport channel to use /// Indicates if only ready clients should receive the message /// - public static bool SendToAll(T msg, int channelId = Channels.DefaultReliable, bool sendToReadyOnly = false) where T : IMessageBase + public static bool SendToAll(T msg, int channelId = Channels.DefaultReliable, bool sendToReadyOnly = false) where T : NetworkMessage { if (!active) { @@ -358,7 +358,7 @@ public static bool SendToAll(T msg, int channelId = Channels.DefaultReliable, /// Message /// Transport channel to use /// - public static bool SendToReady(T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + public static bool SendToReady(T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage { if (!active) { @@ -379,7 +379,7 @@ public static bool SendToReady(T msg, int channelId = Channels.DefaultReliabl /// Should the owner of the object be included /// Transport channel to use /// - public static bool SendToReady(NetworkIdentity identity, T msg, bool includeOwner = true, int channelId = Channels.DefaultReliable) where T : IMessageBase + public static bool SendToReady(NetworkIdentity identity, T msg, bool includeOwner = true, int channelId = Channels.DefaultReliable) where T : NetworkMessage { if (logger.LogEnabled()) logger.Log("Server.SendToReady msgType:" + typeof(T)); @@ -437,7 +437,7 @@ public static bool SendToReady(NetworkIdentity identity, T msg, bool includeO /// Message /// Transport channel to use /// - public static bool SendToReady(NetworkIdentity identity, T msg, int channelId) where T : IMessageBase + public static bool SendToReady(NetworkIdentity identity, T msg, int channelId) where T : NetworkMessage { return SendToReady(identity, msg, true, channelId); } @@ -600,7 +600,7 @@ static void OnError(int connectionId, Exception exception) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { int msgType = MessagePacker.GetId(); if (handlers.ContainsKey(msgType)) @@ -617,7 +617,7 @@ static void OnError(int connectionId, Exception exception) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void RegisterHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { RegisterHandler((_, value) => { handler(value); }, requireAuthentication); } @@ -629,7 +629,7 @@ static void OnError(int connectionId, Exception exception) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { int msgType = MessagePacker.GetId(); handlers[msgType] = MessagePacker.MessageHandler(handler, requireAuthentication); @@ -642,7 +642,7 @@ static void OnError(int connectionId, Exception exception) /// Message type /// Function handler which will be invoked when this message type is received. /// True if the message requires an authenticated connection - public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : IMessageBase, new() + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) where T : NetworkMessage, new() { ReplaceHandler((_, value) => { handler(value); }, requireAuthentication); } @@ -651,7 +651,7 @@ static void OnError(int connectionId, Exception exception) /// Unregisters a handler for a particular message type. /// /// Message type - public static void UnregisterHandler() where T : IMessageBase + public static void UnregisterHandler() where T : NetworkMessage { int msgType = MessagePacker.GetId(); handlers.Remove(msgType); @@ -671,7 +671,7 @@ public static void ClearHandlers() /// Message type /// /// - public static void SendToClientOfPlayer(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + public static void SendToClientOfPlayer(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage { if (identity != null) { diff --git a/Assets/Mirror/Runtime/NetworkWriter.cs b/Assets/Mirror/Runtime/NetworkWriter.cs index 05814e9b0..cdb8ca07e 100644 --- a/Assets/Mirror/Runtime/NetworkWriter.cs +++ b/Assets/Mirror/Runtime/NetworkWriter.cs @@ -536,7 +536,7 @@ public static void WriteUri(this NetworkWriter writer, Uri uri) writer.WriteString(uri.ToString()); } - public static void WriteMessage(this NetworkWriter writer, T msg) where T : IMessageBase + public static void WriteMessage(this NetworkWriter writer, T msg) where T : NetworkMessage { msg.Serialize(writer); } diff --git a/Assets/Mirror/Tests/Editor/ArraySegmentWriterTest.cs b/Assets/Mirror/Tests/Editor/ArraySegmentWriterTest.cs index 0681949d0..8db6786f7 100644 --- a/Assets/Mirror/Tests/Editor/ArraySegmentWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/ArraySegmentWriterTest.cs @@ -11,7 +11,7 @@ public class ArraySegmentWriterTest // ArraySegment is a special case, optimized for no copy and no allocation // other types are generated by the weaver - struct ByteArraySegmentMessage : IMessageBase + struct ByteArraySegmentMessage : NetworkMessage { public ArraySegment array; @@ -88,7 +88,7 @@ public void TestSegmentByteArray() #region ArraySegment - struct IntArraySegmentMessage : IMessageBase + struct IntArraySegmentMessage : NetworkMessage { public ArraySegment array; diff --git a/Assets/Mirror/Tests/Editor/ArrayWriterTest.cs b/Assets/Mirror/Tests/Editor/ArrayWriterTest.cs index fffbe22da..6eee88765 100644 --- a/Assets/Mirror/Tests/Editor/ArrayWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/ArrayWriterTest.cs @@ -4,7 +4,7 @@ namespace Mirror.Tests [TestFixture] public class ArrayWriterTest { - struct ArrayByteMessage : IMessageBase + struct ArrayByteMessage : NetworkMessage { public byte[] array; @@ -62,7 +62,7 @@ public void TestDataByteArray() Assert.That(unpacked.array, Is.EquivalentTo(new byte[] { 3, 4, 5 })); } - struct ArrayIntMessage : IMessageBase + struct ArrayIntMessage : NetworkMessage { public int[] array; diff --git a/Assets/Mirror/Tests/Editor/CustomRWTest.cs b/Assets/Mirror/Tests/Editor/CustomRWTest.cs index d7363278b..133a8be16 100644 --- a/Assets/Mirror/Tests/Editor/CustomRWTest.cs +++ b/Assets/Mirror/Tests/Editor/CustomRWTest.cs @@ -32,7 +32,7 @@ public static MockQuest ReadQuest(this NetworkReader reader) [TestFixture] public class CustomRWTest { - struct QuestMessage : IMessageBase + struct QuestMessage : NetworkMessage { public MockQuest quest; diff --git a/Assets/Mirror/Tests/Editor/EnumReadWriteTests.cs b/Assets/Mirror/Tests/Editor/EnumReadWriteTests.cs index 7bae16411..9272c2d7a 100644 --- a/Assets/Mirror/Tests/Editor/EnumReadWriteTests.cs +++ b/Assets/Mirror/Tests/Editor/EnumReadWriteTests.cs @@ -23,7 +23,7 @@ public static EnumReadWriteTests.MyCustomEnum ReadMyCustomEnum(this NetworkReade } public class EnumReadWriteTests { - public struct ByteMessage : IMessageBase + public struct ByteMessage : NetworkMessage { public MyByteEnum byteEnum; @@ -36,7 +36,7 @@ public enum MyByteEnum : byte A, B, C, D } - public struct ShortMessage : IMessageBase + public struct ShortMessage : NetworkMessage { public MyShortEnum shortEnum; @@ -49,7 +49,7 @@ public enum MyShortEnum : short E, F, G, H } - public struct CustomMessage : IMessageBase + public struct CustomMessage : NetworkMessage { public MyCustomEnum customEnum; @@ -97,7 +97,7 @@ public void CustomWriterIsUsedForEnum() // custom writer should write N if it sees O Assert.That(clientMsg.customEnum, Is.EqualTo(MyCustomEnum.N)); } - T SerializeAndDeserializeMessage(T msg) where T : IMessageBase, new() + T SerializeAndDeserializeMessage(T msg) where T : NetworkMessage, new() { NetworkWriter writer = new NetworkWriter(); diff --git a/Assets/Mirror/Tests/Editor/MessageBaseTests.cs b/Assets/Mirror/Tests/Editor/MessageBaseTests.cs index e2fad127f..adbd97960 100644 --- a/Assets/Mirror/Tests/Editor/MessageBaseTests.cs +++ b/Assets/Mirror/Tests/Editor/MessageBaseTests.cs @@ -2,7 +2,7 @@ namespace Mirror.Tests { - struct TestMessage : IMessageBase + struct TestMessage : NetworkMessage { public int IntValue; public string StringValue; @@ -30,7 +30,7 @@ public void Serialize(NetworkWriter writer) } } - struct WovenTestMessage : IMessageBase + struct WovenTestMessage : NetworkMessage { public int IntValue; public string StringValue; diff --git a/Assets/Mirror/Tests/Editor/ScriptableObjectWriterTest.cs b/Assets/Mirror/Tests/Editor/ScriptableObjectWriterTest.cs index 3c1e4b061..cdc27cf28 100644 --- a/Assets/Mirror/Tests/Editor/ScriptableObjectWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/ScriptableObjectWriterTest.cs @@ -16,7 +16,7 @@ public class ScriptableObjectWriterTest // other types are generated by the weaver - struct ScriptableObjectMessage : IMessageBase + struct ScriptableObjectMessage : NetworkMessage { public MyScriptableObject scriptableObject; diff --git a/Assets/Mirror/Tests/Editor/StructMessagesTests.cs b/Assets/Mirror/Tests/Editor/StructMessagesTests.cs index 25d5e7898..a1a9df9c2 100644 --- a/Assets/Mirror/Tests/Editor/StructMessagesTests.cs +++ b/Assets/Mirror/Tests/Editor/StructMessagesTests.cs @@ -2,7 +2,7 @@ namespace Mirror.Tests.StructMessages { - public struct SomeStructMessage : IMessageBase + public struct SomeStructMessage : NetworkMessage { public int someValue; diff --git a/doc/Guides/Communications/NetworkMessages.md b/doc/Guides/Communications/NetworkMessages.md index 511d49207..cf4ac95ed 100644 --- a/doc/Guides/Communications/NetworkMessages.md +++ b/doc/Guides/Communications/NetworkMessages.md @@ -2,12 +2,12 @@ For the most part we recommend the high level [Commands and RPC](RemoteActions.md) calls and [SyncVar](../Sync/index.md), but you can also send low level network messages. This can be useful if you want clients to send messages that are not tied to game objects, such as logging, analytics or profiling information. -Network Messages need to be structs in order to avoid runtime allocations, and they need to implement the IMessageBase interface. This interface requires Serialize and Deserialize functions that take writer and reader objects. You can implement these functions yourself, but we recommend you let them empty and let Mirror generate them for you. +Network Messages need to be structs in order to avoid runtime allocations, and they need to implement the NetworkMessage interface. This interface requires Serialize and Deserialize functions that take writer and reader objects. You can implement these functions yourself, but we recommend you let them empty and let Mirror generate them for you. The interface looks like this: ``` cs -public interface IMessageBase +public interface NetworkMessage { // Deserialize the contents of the reader into this message public virtual void Deserialize(NetworkReader reader) {} @@ -19,7 +19,7 @@ public interface IMessageBase The auto generated Serialize/Deserialize can efficiently deal any [supported mirror type](../DataTypes.md) . Make your members public. If you need class members or complex containers such as List and Dictionary, you must implement the Serialize and Deserialize methods yourself. -To send a message, use the `Send()` method on the NetworkClient, NetworkServer, and NetworkConnection classes which work the same way. It takes a message struct that implements IMessageBase. The code below demonstrates how to send and handle a message: +To send a message, use the `Send()` method on the NetworkClient, NetworkServer, and NetworkConnection classes which work the same way. It takes a message struct that implements NetworkMessage. The code below demonstrates how to send and handle a message: To declare a custom network message class and use it: @@ -29,7 +29,7 @@ using Mirror; public class Scores : MonoBehaviour { - public struct ScoreMessage : IMessageBase + public struct ScoreMessage : NetworkMessage { public int score; public Vector3 scorePos;