From bfb40202793f2f7f2c9c73272f01a477b23edfa2 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Nov 2018 21:34:48 -0500 Subject: rewrite multiplayer sync to use generic callbacks from client/server for better extensibility (#480) --- src/SMAPI/Framework/Networking/MessageType.cs | 26 +++++ src/SMAPI/Framework/Networking/MultiplayerPeer.cs | 6 +- src/SMAPI/Framework/Networking/SLidgrenClient.cs | 37 +++---- src/SMAPI/Framework/Networking/SLidgrenServer.cs | 122 +++++++++++++++++++++- 4 files changed, 160 insertions(+), 31 deletions(-) create mode 100644 src/SMAPI/Framework/Networking/MessageType.cs (limited to 'src/SMAPI/Framework/Networking') diff --git a/src/SMAPI/Framework/Networking/MessageType.cs b/src/SMAPI/Framework/Networking/MessageType.cs new file mode 100644 index 00000000..bd9acfa9 --- /dev/null +++ b/src/SMAPI/Framework/Networking/MessageType.cs @@ -0,0 +1,26 @@ +using StardewValley; + +namespace StardewModdingAPI.Framework.Networking +{ + /// Network message types recognised by SMAPI and Stardew Valley. + internal enum MessageType : byte + { + /********* + ** SMAPI + *********/ + /// A data message intended for mods to consume. + ModMessage = 254, + + /// Metadata context about a player synced by SMAPI. + ModContext = 255, + + /********* + ** Vanilla + *********/ + /// Metadata about the host server sent to a farmhand. + ServerIntroduction = Multiplayer.serverIntroduction, + + /// Metadata about a player sent to a farmhand or server. + PlayerIntroduction = Multiplayer.playerIntroduction + } +} diff --git a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs index c7f8ffad..e703dbb1 100644 --- a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs +++ b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; using Lidgren.Network; -using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking @@ -95,7 +94,8 @@ namespace StardewModdingAPI.Framework.Networking /// The player's unique ID. /// The metadata to copy. /// The client through which to send messages. - public static MultiplayerPeer ForConnectionToHost(long playerID, RemoteContextModel model, SLidgrenClient client) + /// Whether this connection is for the host player. + public static MultiplayerPeer ForConnectionToHost(long playerID, RemoteContextModel model, SLidgrenClient client, bool isHost) { return new MultiplayerPeer( playerID: playerID, @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Framework.Networking server: null, serverConnection: null, client: client, - isHost: true + isHost: isHost ); } diff --git a/src/SMAPI/Framework/Networking/SLidgrenClient.cs b/src/SMAPI/Framework/Networking/SLidgrenClient.cs index 9dfdba15..c05e6b76 100644 --- a/src/SMAPI/Framework/Networking/SLidgrenClient.cs +++ b/src/SMAPI/Framework/Networking/SLidgrenClient.cs @@ -1,44 +1,38 @@ using System; -using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking { - /// A multiplayer client used to connect to a hosted server. This is an implementation of that adds support for SMAPI's metadata context exchange. + /// A multiplayer client used to connect to a hosted server. This is an implementation of with callbacks for SMAPI functionality. internal class SLidgrenClient : LidgrenClient { /********* ** Properties *********/ - /// Get the metadata to include in a metadata message sent to other players. - private readonly Func GetMetadataMessageFields; - - /// The method to call when receiving a custom SMAPI message from the server, which returns whether the message was processed. - private readonly Func TryProcessMessage; + /// A callback to raise when receiving a message. This receives the client instance, incoming message, and a callback to run the default logic. + private readonly Action OnProcessingMessage; + /// A callback to raise when sending a message. This receives the client instance, outgoing message, and a callback to run the default logic. + private readonly Action OnSendingMessage; /********* ** Public methods *********/ /// Construct an instance. /// The remote address being connected. - /// Get the metadata to include in a metadata message sent to other players. - /// The method to call when receiving a custom SMAPI message from the server, which returns whether the message was processed.. - public SLidgrenClient(string address, Func getMetadataMessageFields, Func tryProcessMessage) + /// A callback to raise when receiving a message. This receives the client instance, incoming message, and a callback to run the default logic. + /// A callback to raise when sending a message. This receives the client instance, outgoing message, and a callback to run the default logic. + public SLidgrenClient(string address, Action onProcessingMessage, Action onSendingMessage) : base(address) { - this.GetMetadataMessageFields = getMetadataMessageFields; - this.TryProcessMessage = tryProcessMessage; + this.OnProcessingMessage = onProcessingMessage; + this.OnSendingMessage = onSendingMessage; } - /// Send the metadata needed to connect with a remote server. - public override void sendPlayerIntroduction() + /// Send a message to the connected peer. + public override void sendMessage(OutgoingMessage message) { - // send custom intro - if (this.getUserID() != "") - Game1.player.userID.Value = this.getUserID(); - this.sendMessage(SMultiplayer.ContextSyncMessageID, this.GetMetadataMessageFields()); - base.sendPlayerIntroduction(); + this.OnSendingMessage(this, message, () => base.sendMessage(message)); } @@ -49,10 +43,7 @@ namespace StardewModdingAPI.Framework.Networking /// The message to process. protected override void processIncomingMessage(IncomingMessage message) { - if (this.TryProcessMessage(this, message)) - return; - - base.processIncomingMessage(message); + this.OnProcessingMessage(this, message, () => base.processIncomingMessage(message)); } } } diff --git a/src/SMAPI/Framework/Networking/SLidgrenServer.cs b/src/SMAPI/Framework/Networking/SLidgrenServer.cs index 971eb66d..060b433b 100644 --- a/src/SMAPI/Framework/Networking/SLidgrenServer.cs +++ b/src/SMAPI/Framework/Networking/SLidgrenServer.cs @@ -1,5 +1,11 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Reflection; using Lidgren.Network; +using StardewModdingAPI.Framework.Reflection; +using StardewModdingAPI.Patches; +using StardewValley; using StardewValley.Network; namespace StardewModdingAPI.Framework.Networking @@ -10,8 +16,27 @@ namespace StardewModdingAPI.Framework.Networking /********* ** Properties *********/ - /// A method which sends a message through a specific connection. - private readonly MethodInfo SendMessageToConnectionMethod; + + /// The constructor for the internal NetBufferReadStream type. + private readonly ConstructorInfo NetBufferReadStreamConstructor = SLidgrenServer.GetNetBufferReadStreamConstructor(); + + /// The constructor for the internal NetBufferWriteStream type. + private readonly ConstructorInfo NetBufferWriteStreamConstructor = SLidgrenServer.GetNetBufferWriteStreamConstructor(); + + /// A method which reads farmer data from the given binary reader. + private readonly Func ReadFarmer; + + /// A callback to raise when receiving a message. This receives the server instance, raw/parsed incoming message, and a callback to run the default logic. + private readonly Action OnProcessingMessage; + + /// A callback to raise when sending a message. This receives the server instance, outgoing connection, outgoing message, target player ID, and a callback to run the default logic. + private readonly Action OnSendingMessage; + + /// The peer connections. + private readonly Bimap Peers; + + /// The underlying net server. + private readonly IReflectedField Server; /********* @@ -19,18 +44,105 @@ namespace StardewModdingAPI.Framework.Networking *********/ /// Construct an instance. /// The underlying game server. - public SLidgrenServer(IGameServer gameServer) + /// Simplifies access to private code. + /// A method which reads farmer data from the given binary reader. + /// A callback to raise when receiving a message. This receives the server instance, raw/parsed incoming message, and a callback to run the default logic. + /// A callback to raise when sending a message. This receives the server instance, outgoing connection, outgoing message, and a callback to run the default logic. + public SLidgrenServer(IGameServer gameServer, Reflector reflection, Func readFarmer, Action onProcessingMessage, Action onSendingMessage) : base(gameServer) { - this.SendMessageToConnectionMethod = typeof(LidgrenServer).GetMethod(nameof(LidgrenServer.sendMessage), BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(NetConnection), typeof(OutgoingMessage) }, null); + this.ReadFarmer = readFarmer; + this.OnProcessingMessage = onProcessingMessage; + this.OnSendingMessage = onSendingMessage; + this.Peers = reflection.GetField>(this, "peers").GetValue(); + this.Server = reflection.GetField(this, "server"); } /// Send a message to a remote server. /// The network connection. /// The message to send. + /// This is an implementation of which calls . This method is invoked via . public void SendMessage(NetConnection connection, OutgoingMessage message) { - this.SendMessageToConnectionMethod.Invoke(this, new object[] { connection, message }); + this.OnSendingMessage(this, connection, message, () => + { + NetServer server = this.Server.GetValue(); + NetOutgoingMessage netMessage = server.CreateMessage(); + using (Stream bufferWriteStream = (Stream)this.NetBufferWriteStreamConstructor.Invoke(new object[] { netMessage })) + using (BinaryWriter writer = new BinaryWriter(bufferWriteStream)) + message.Write(writer); + + server.SendMessage(netMessage, connection, NetDeliveryMethod.ReliableOrdered); + }); + } + + /// Parse a data message from a client. + /// The raw network message to parse. + /// This is an implementation of which calls . This method is invoked via . + [SuppressMessage("ReSharper", "AccessToDisposedClosure", Justification = "The callback is invoked synchronously.")] + public bool ParseDataMessageFromClient(NetIncomingMessage rawMessage) + { + // add hook to call multiplayer core + NetConnection peer = rawMessage.SenderConnection; + using (IncomingMessage message = new IncomingMessage()) + using (Stream readStream = (Stream)this.NetBufferReadStreamConstructor.Invoke(new object[] { rawMessage })) + using (BinaryReader reader = new BinaryReader(readStream)) + { + while (rawMessage.LengthBits - rawMessage.Position >= 8) + { + message.Read(reader); + this.OnProcessingMessage(this, rawMessage, message, () => + { + if (this.Peers.ContainsLeft(message.FarmerID) && this.Peers[message.FarmerID] == peer) + this.gameServer.processIncomingMessage(message); + else if (message.MessageType == Multiplayer.playerIntroduction) + { + NetFarmerRoot farmer = this.ReadFarmer(message.Reader); + this.gameServer.checkFarmhandRequest("", farmer, msg => this.SendMessage(peer, msg), () => this.Peers[farmer.Value.UniqueMultiplayerID] = peer); + } + }); + } + } + + return false; + } + + + /********* + ** Private methods + *********/ + /// Get the constructor for the internal NetBufferReadStream type. + private static ConstructorInfo GetNetBufferReadStreamConstructor() + { + // get type + string typeName = $"StardewValley.Network.NetBufferReadStream, {Constants.GameAssemblyName}"; + Type type = Type.GetType(typeName); + if (type == null) + throw new InvalidOperationException($"Can't find type: {typeName}"); + + // get constructor + ConstructorInfo constructor = type.GetConstructor(new[] { typeof(NetBuffer) }); + if (constructor == null) + throw new InvalidOperationException($"Can't find constructor for type: {typeName}"); + + return constructor; + } + + /// Get the constructor for the internal NetBufferWriteStream type. + private static ConstructorInfo GetNetBufferWriteStreamConstructor() + { + // get type + string typeName = $"StardewValley.Network.NetBufferWriteStream, {Constants.GameAssemblyName}"; + Type type = Type.GetType(typeName); + if (type == null) + throw new InvalidOperationException($"Can't find type: {typeName}"); + + // get constructor + ConstructorInfo constructor = type.GetConstructor(new[] { typeof(NetBuffer) }); + if (constructor == null) + throw new InvalidOperationException($"Can't find constructor for type: {typeName}"); + + return constructor; } } } -- cgit