From 506b51f1892053d1d8251d0cf7c13064e992c658 Mon Sep 17 00:00:00 2001 From: cpw Date: Fri, 22 Jun 2018 14:38:53 -0400 Subject: [PATCH] A much more straightforward networking system. --- .../minecraftforge/common/UsernameCache.java | 70 ++++++------ .../net/minecraftforge/fml/ModContainer.java | 1 - .../network/simpleimpl/IMessageHandler.java | 6 +- .../SimpleChannelHandlerWrapper.java | 4 +- .../simpleimpl/SimpleNetworkWrapper.java | 4 +- .../minecraftforge/fml/loading/FMLLoader.java | 7 ++ .../minecraftforge/fml/network/Network.java | 45 ++++++++ .../fml/network/NetworkEvent.java | 101 ++++++++++++++++++ .../fml/network/NetworkHooks.java | 9 +- .../fml/network/NetworkInstance.java | 58 +--------- .../fml/network/NetworkRegistry.java | 11 +- .../EventNetworkChannel.java} | 33 +++++- .../network/simple/IndexedMessageCodec.java | 16 +-- .../fml/network/simple/MessageContext.java | 70 ------------ .../fml/network/simple/SimpleChannel.java | 17 +-- .../debug/item/MapDataTest.java | 4 +- .../fml/test/simplenet/SimpleNetHandler1.java | 4 +- .../fml/test/simplenet/SimpleNetHandler2.java | 4 +- 18 files changed, 264 insertions(+), 200 deletions(-) create mode 100644 src/main/java/net/minecraftforge/fml/network/Network.java create mode 100644 src/main/java/net/minecraftforge/fml/network/NetworkEvent.java rename src/main/java/net/minecraftforge/fml/network/{Networking.java => event/EventNetworkChannel.java} (51%) delete mode 100644 src/main/java/net/minecraftforge/fml/network/simple/MessageContext.java diff --git a/src/main/java/net/minecraftforge/common/UsernameCache.java b/src/main/java/net/minecraftforge/common/UsernameCache.java index 704cce3d8..bc86da57d 100644 --- a/src/main/java/net/minecraftforge/common/UsernameCache.java +++ b/src/main/java/net/minecraftforge/common/UsernameCache.java @@ -19,28 +19,32 @@ package net.minecraftforge.common; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.File; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.IOException; import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.UUID; import javax.annotation.Nullable; +import com.google.common.base.Charsets; +import net.minecraft.world.storage.ThreadedFileIOBase; +import net.minecraftforge.fml.loading.FMLLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.io.Files; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; /** * Caches player's last known usernames @@ -52,19 +56,18 @@ import com.google.gson.JsonSyntaxException; */ public final class UsernameCache { - private static Map map = Maps.newHashMap(); + private static Map map = new HashMap<>(); - private static final Charset charset = StandardCharsets.UTF_8; - - private static final File saveFile = new File( /* The minecraft dir */(File) FMLInjectionData.data()[6], "usernamecache.json"); + private static final Path saveFile = FMLLoader.getGamePath().resolve("usernamecache.json"); private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final Logger log = LogManager.getLogger(ForgeVersion.MOD_ID + ".UsernameCache"); + private static final Logger LOGGER = LogManager.getLogger(UsernameCache.class); + private static final Marker USRCACHE = MarkerManager.getMarker("USERNAMECACHE"); private UsernameCache() {} /** - * Set a player's current username + * Set a player's current usernamee * * @param uuid * the player's {@link java.util.UUID UUID} @@ -73,8 +76,8 @@ public final class UsernameCache { */ protected static void setUsername(UUID uuid, String username) { - checkNotNull(uuid); - checkNotNull(username); + Objects.requireNonNull(uuid); + Objects.requireNonNull(username); if (username.equals(map.get(uuid))) return; @@ -91,7 +94,7 @@ public final class UsernameCache { */ protected static boolean removeUsername(UUID uuid) { - checkNotNull(uuid); + Objects.requireNonNull(uuid); if (map.remove(uuid) != null) { @@ -115,7 +118,7 @@ public final class UsernameCache { @Nullable public static String getLastKnownUsername(UUID uuid) { - checkNotNull(uuid); + Objects.requireNonNull(uuid); return map.get(uuid); } @@ -128,7 +131,7 @@ public final class UsernameCache { */ public static boolean containsUUID(UUID uuid) { - checkNotNull(uuid); + Objects.requireNonNull(uuid); return map.containsKey(uuid); } @@ -155,32 +158,31 @@ public final class UsernameCache { */ protected static void load() { - if (!saveFile.exists()) return; + if (!Files.exists(saveFile)) return; - try + try (final BufferedReader reader = Files.newBufferedReader(saveFile, Charsets.UTF_8)) { - - String json = Files.toString(saveFile, charset); - Type type = new TypeToken>() { private static final long serialVersionUID = 1L; }.getType(); - - map = gson.fromJson(json, type); + Type type = new TypeToken>(){}.getType(); + map = gson.fromJson(reader, type); } - catch (JsonSyntaxException e) + catch (JsonSyntaxException | IOException e) { - log.error("Could not parse username cache file as valid json, deleting file", e); - saveFile.delete(); - } - catch (IOException e) - { - log.error("Failed to read username cache file from disk, deleting file", e); - saveFile.delete(); + LOGGER.error(USRCACHE,"Could not parse username cache file as valid json, deleting file {}", saveFile, e); + try + { + Files.delete(saveFile); + } + catch (IOException e1) + { + LOGGER.error(USRCACHE,"Could not delete file {}", saveFile.toString()); + } } finally { // Can sometimes occur when the json file is malformed if (map == null) { - map = Maps.newHashMap(); + map = new HashMap<>(); } } } diff --git a/src/main/java/net/minecraftforge/fml/ModContainer.java b/src/main/java/net/minecraftforge/fml/ModContainer.java index 0a28de436..4e8816254 100644 --- a/src/main/java/net/minecraftforge/fml/ModContainer.java +++ b/src/main/java/net/minecraftforge/fml/ModContainer.java @@ -20,7 +20,6 @@ package net.minecraftforge.fml; import net.minecraftforge.fml.language.IModInfo; -import net.minecraftforge.fml.network.Networking; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java index fae8ecf38..962f5a3b4 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java @@ -20,10 +20,10 @@ package net.minecraftforge.fml.common.network.simpleimpl; -import net.minecraftforge.fml.network.simple.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; /** - * A message handler based on {@link IMessage}. Implement and override {@link #onMessage(IMessage, MessageContext)} to + * A message handler based on {@link IMessage}. Implement and override {@link #onMessage(IMessage, NetworkEvent.Context)} to * process your packet. Supply the class to {@link SimpleNetworkWrapper#registerMessage(Class, Class, int, Side)} * to register both the message type and it's associated handler. * @@ -41,5 +41,5 @@ public interface IMessageHandler { * @param message The message * @return an optional return message */ - REPLY onMessage(REQ message, MessageContext ctx); + REPLY onMessage(REQ message, NetworkEvent.Context ctx); } diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java index f57d8ec66..9da6a432d 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java @@ -20,7 +20,7 @@ package net.minecraftforge.fml.common.network.simpleimpl; import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.network.simple.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; import net.minecraft.network.INetHandler; import net.minecraftforge.fml.common.FMLLog; @@ -52,7 +52,7 @@ public class SimpleChannelHandlerWrapper { - * public Message2 onMessage(Message1 message, MessageContext ctx) { + * public Message2 onMessage(Message1 message, Context ctx) { * // do something and generate reply message * return aMessage2Object; * } * } * // Message2Handler expects input of type Message2 and returns no message (IMessage) * public Message2Handler implements IMessageHandler { - * public IMessage onMessage(Message2 message, MessageContext ctx) { + * public IMessage onMessage(Message2 message, Context ctx) { * // handle the message 2 response message at the other end * // no reply for this message - return null * return null; diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java b/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java index e821ad24d..7b1893ec8 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java @@ -57,6 +57,7 @@ public class FMLLoader private static LoadingModList loadingModList; private static ClassLoader launchClassLoader; private static RuntimeDistCleaner runtimeDistCleaner; + private static Path gamePath; static void onInitialLoad(IEnvironment environment, Set otherServices) throws IncompatibleEnvironmentException { @@ -124,6 +125,7 @@ public class FMLLoader fmlLog.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName()); throw new RuntimeException("Incompatible launch handler found"); } + gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath()); FMLCommonLaunchHandler commonLaunchHandler = (FMLCommonLaunchHandler)launchHandler.get(); commonLaunchHandler.setup(environment); @@ -192,4 +194,9 @@ public class FMLLoader { return launchClassLoader; } + + public static Path getGamePath() + { + return gamePath; + } } diff --git a/src/main/java/net/minecraftforge/fml/network/Network.java b/src/main/java/net/minecraftforge/fml/network/Network.java new file mode 100644 index 000000000..43d77dc68 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/network/Network.java @@ -0,0 +1,45 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.network; + +import net.minecraft.network.PacketBuffer; + +import java.util.function.BiFunction; +import java.util.function.Supplier; + +public enum Network +{ + PLAYSERVER(NetworkEvent.ClientCustomPayloadEvent::new), + PLAYCLIENT(NetworkEvent.ServerCustomPayloadEvent::new), + LOGINSERVER(NetworkEvent.ClientCustomPayloadEvent::new), + LOGINCLIENT(NetworkEvent.ServerCustomPayloadEvent::new); + + private final BiFunction, NetworkEvent> eventSupplier; + + Network(BiFunction, NetworkEvent> eventSupplier) + { + this.eventSupplier = eventSupplier; + } + + public NetworkEvent getEvent(final PacketBuffer buffer, final Supplier manager) { + return this.eventSupplier.apply(buffer, manager); + } + +} diff --git a/src/main/java/net/minecraftforge/fml/network/NetworkEvent.java b/src/main/java/net/minecraftforge/fml/network/NetworkEvent.java new file mode 100644 index 000000000..0948d4cb9 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/network/NetworkEvent.java @@ -0,0 +1,101 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.network; + +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.INetHandler; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.eventbus.api.Event; + +import java.util.function.Supplier; + +public class NetworkEvent extends Event +{ + private final PacketBuffer payload; + private final Supplier source; + + private NetworkEvent(PacketBuffer payload, Supplier source) + { + this.payload = payload; + this.source = source; + } + + public PacketBuffer getPayload() + { + return payload; + } + + public Supplier getSource() + { + return source; + } + + public static class ServerCustomPayloadEvent extends NetworkEvent + { + ServerCustomPayloadEvent(final PacketBuffer payload, final Supplier source) { + super(payload, source); + } + } + public static class ClientCustomPayloadEvent extends NetworkEvent + { + ClientCustomPayloadEvent(final PacketBuffer payload, final Supplier source) { + super(payload, source); + } + } + + /** + * Context for {@link NetworkEvent} + */ + public static class Context + { + /** + * The {@link INetHandler} for this message. It could be a client or server handler, depending + * on the {@link #side} received. + */ + private final INetHandler netHandler; + + /** + * The {@link Network} this message has been received on + */ + private final Network side; + + Context(NetworkManager netHandler, Network side) + { + this.netHandler = netHandler.getNetHandler(); + this.side = side; + } + + public Network getSide() { + return side; + } + + public NetHandlerPlayServer getServerHandler() + { + return (NetHandlerPlayServer) netHandler; + } + + public NetHandlerPlayClient getClientHandler() + { + return (NetHandlerPlayClient) netHandler; + } + } +} diff --git a/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java b/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java index ae7c87710..40503d389 100644 --- a/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java +++ b/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java @@ -27,7 +27,6 @@ import net.minecraft.network.handshake.client.C00Handshake; import net.minecraft.network.play.client.CPacketCustomPayload; import net.minecraft.network.play.server.SPacketCustomPayload; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.common.registry.EntityRegistry; import java.util.Objects; @@ -63,22 +62,22 @@ public class NetworkHooks public static void onServerCustomPayload(final SPacketCustomPayload packet, final NetworkManager manager) { NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())). - ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.PLAYSERVER, packet.getBufferData(), manager)); + ifPresent(ni->ni.dispatch(Network.PLAYSERVER, packet.getBufferData(), manager)); } public static void onClientCustomPayload(final CPacketCustomPayload packet, final NetworkManager manager) { NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())). - ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.PLAYCLIENT, packet.getBufferData(), manager)); + ifPresent(ni->ni.dispatch(Network.PLAYCLIENT, packet.getBufferData(), manager)); } public static void onServerLoginCustomPayload(final SPacketCustomPayload packet, final NetworkManager manager) { NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())). - ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.LOGINSERVER, packet.getBufferData(), manager)); + ifPresent(ni->ni.dispatch(Network.LOGINSERVER, packet.getBufferData(), manager)); } public static void onClientLoginCustomPayload(final CPacketCustomPayload packet, final NetworkManager manager) { NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())). - ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.LOGINCLIENT, packet.getBufferData(), manager)); + ifPresent(ni->ni.dispatch(Network.LOGINCLIENT, packet.getBufferData(), manager)); } public static void registerServerChannel(NetworkManager manager, C00Handshake packet) diff --git a/src/main/java/net/minecraftforge/fml/network/NetworkInstance.java b/src/main/java/net/minecraftforge/fml/network/NetworkInstance.java index a2eb0433c..ad4dbeb04 100644 --- a/src/main/java/net/minecraftforge/fml/network/NetworkInstance.java +++ b/src/main/java/net/minecraftforge/fml/network/NetworkInstance.java @@ -26,7 +26,6 @@ import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventListener; -import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -38,24 +37,6 @@ public class NetworkInstance return channelName.toString(); } - public enum NetworkSide { - PLAYSERVER(NetworkEvent.ServerCustomPayloadEvent::new), - PLAYCLIENT(NetworkEvent.ClientCustomPayloadEvent::new), - LOGINSERVER(NetworkEvent.ServerCustomPayloadEvent::new), - LOGINCLIENT(NetworkEvent.ClientCustomPayloadEvent::new); - - private final BiFunction eventSupplier; - - NetworkSide(BiFunction eventSupplier) - { - this.eventSupplier = eventSupplier; - } - - public NetworkEvent getEvent(final PacketBuffer buffer, final NetworkManager manager) { - return this.eventSupplier.apply(buffer, manager); - } - - } private final ResourceLocation channelName; private final Supplier networkProtocolVersion; private final Predicate clientAcceptedVersions; @@ -76,9 +57,9 @@ public class NetworkInstance } - public void addListener(Consumer serverEventListener) + public void addListener(Consumer eventListener) { - this.networkEventBus.addListener(serverEventListener); + this.networkEventBus.addListener(eventListener); } public void registerObject(final Object object) { @@ -89,41 +70,10 @@ public class NetworkInstance this.networkEventBus.unregister(object); } - void dispatch(final NetworkSide side, final PacketBuffer bufferData, final NetworkManager manager) + void dispatch(final Network side, final PacketBuffer bufferData, final NetworkManager manager) { - this.networkEventBus.post(side.getEvent(bufferData,manager)); + this.networkEventBus.post(side.getEvent(bufferData,()->new NetworkEvent.Context(manager, side))); } - public static class NetworkEvent extends Event { - private final PacketBuffer payload; - private final NetworkManager source; - - private NetworkEvent(PacketBuffer payload, NetworkManager source) - { - this.payload = payload; - this.source = source; - } - - public PacketBuffer getPayload() - { - return payload; - } - - public NetworkManager getSource() - { - return source; - } - - public static class ServerCustomPayloadEvent extends NetworkEvent { - ServerCustomPayloadEvent(final PacketBuffer payload, final NetworkManager source) { - super(payload, source); - } - } - public static class ClientCustomPayloadEvent extends NetworkEvent { - ClientCustomPayloadEvent(final PacketBuffer payload, final NetworkManager source) { - super(payload, source); - } - } - } } diff --git a/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java b/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java index 947393ee8..5fd89e264 100644 --- a/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java +++ b/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java @@ -21,6 +21,7 @@ package net.minecraftforge.fml.network; import io.netty.util.AttributeKey; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.network.event.EventNetworkChannel; import net.minecraftforge.fml.network.simple.SimpleChannel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -50,13 +51,21 @@ public class NetworkRegistry public static SimpleChannel newSimpleChannel(final ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) { + return new SimpleChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions)); + } + + public static EventNetworkChannel newEventChannel(final ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) { + return new EventNetworkChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions)); + } + private static NetworkInstance createInstance(ResourceLocation name, Supplier networkProtocolVersion, Predicate clientAcceptedVersions, Predicate serverAcceptedVersions) + { final NetworkInstance networkInstance = new NetworkInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions); if (instances.containsKey(name)) { LOGGER.error(NETREGISTRY, "Network channel {} already registered.", name); throw new IllegalArgumentException("Network Channel {"+ name +"} already registered"); } instances.put(name, networkInstance); - return new SimpleChannel(networkInstance); + return networkInstance; } static Optional findTarget(ResourceLocation resourceLocation) diff --git a/src/main/java/net/minecraftforge/fml/network/Networking.java b/src/main/java/net/minecraftforge/fml/network/event/EventNetworkChannel.java similarity index 51% rename from src/main/java/net/minecraftforge/fml/network/Networking.java rename to src/main/java/net/minecraftforge/fml/network/event/EventNetworkChannel.java index 54d67df37..de7cb88c8 100644 --- a/src/main/java/net/minecraftforge/fml/network/Networking.java +++ b/src/main/java/net/minecraftforge/fml/network/event/EventNetworkChannel.java @@ -17,9 +17,34 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.network; +package net.minecraftforge.fml.network.event; -public class Networking +import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraftforge.fml.network.NetworkInstance; + +import java.util.function.Consumer; + +public class EventNetworkChannel { - public enum Type { SIMPLE, EVENT, NONE } -} + private final NetworkInstance instance; + + public EventNetworkChannel(NetworkInstance instance) + { + this.instance = instance; + } + + public void addListener(Consumer eventListener) + { + instance.addListener(eventListener); + } + + public void registerObject(Object object) + { + instance.registerObject(object); + } + + public void unregisterObject(Object object) + { + instance.unregisterObject(object); + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/fml/network/simple/IndexedMessageCodec.java b/src/main/java/net/minecraftforge/fml/network/simple/IndexedMessageCodec.java index 865afbb99..1a08fb1a6 100644 --- a/src/main/java/net/minecraftforge/fml/network/simple/IndexedMessageCodec.java +++ b/src/main/java/net/minecraftforge/fml/network/simple/IndexedMessageCodec.java @@ -22,6 +22,7 @@ package net.minecraftforge.fml.network.simple; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap; import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -46,9 +47,9 @@ public class IndexedMessageCodec private final Optional> encoder; private final Optional> decoder; private final int index; - private final BiConsumer> messageConsumer; + private final BiConsumer> messageConsumer; private final Class messageType; - public CodecIndex(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) + public CodecIndex(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { this.index = index; this.messageType = messageType; @@ -61,13 +62,16 @@ public class IndexedMessageCodec } - private static void tryDecode(PacketBuffer payload, Supplier context, CodecIndex codec) + private static void tryDecode(PacketBuffer payload, Supplier context, CodecIndex codec) { codec.decoder.map(d->d.apply(payload)).ifPresent(m->codec.messageConsumer.accept(m, context)); } private static void tryEncode(PacketBuffer target, M message, CodecIndex codec) { - codec.encoder.ifPresent(c->c.accept(message, target)); + codec.encoder.ifPresent(encoder->{ + target.writeByte(codec.index & 0xff); + encoder.accept(message, target); + }); } public void build(MSG message, PacketBuffer target) { @@ -80,7 +84,7 @@ public class IndexedMessageCodec tryEncode(target, message, codecIndex); } - void consume(final PacketBuffer payload, Supplier context) { + void consume(final PacketBuffer payload, Supplier context) { short discriminator = payload.readUnsignedByte(); final CodecIndex codecIndex = indicies.get(discriminator); if (codecIndex == null) { @@ -90,7 +94,7 @@ public class IndexedMessageCodec tryDecode(payload, context, codecIndex); } - void addCodecIndex(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { + void addCodecIndex(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { new CodecIndex<>(index, messageType, encoder, decoder, messageConsumer); } } diff --git a/src/main/java/net/minecraftforge/fml/network/simple/MessageContext.java b/src/main/java/net/minecraftforge/fml/network/simple/MessageContext.java deleted file mode 100644 index b22f1bd19..000000000 --- a/src/main/java/net/minecraftforge/fml/network/simple/MessageContext.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.network.simple; - -import net.minecraft.client.network.NetHandlerPlayClient; -import net.minecraft.network.INetHandler; -import net.minecraft.network.NetHandlerPlayServer; -import net.minecraft.network.NetworkManager; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.network.NetworkInstance; - -/** - * Context for the {@link IMessageHandler} - * - * @author cpw - * - */ -public class MessageContext { - /** - * The {@link INetHandler} for this message. It could be a client or server handler, depending - * on the {@link #side} received. - */ - private final INetHandler netHandler; - - /** - * The {@link NetworkInstance.NetworkSide} this message has been received on - */ - private final NetworkInstance.NetworkSide side; - /** - * @param netHandler - * @param side - */ - MessageContext(NetworkManager netHandler, NetworkInstance.NetworkSide side) - { - this.netHandler = netHandler.getNetHandler(); - this.side = side; - } - - public NetworkInstance.NetworkSide getSide() { - return side; - } - - public NetHandlerPlayServer getServerHandler() - { - return (NetHandlerPlayServer) netHandler; - } - - public NetHandlerPlayClient getClientHandler() - { - return (NetHandlerPlayClient) netHandler; - } -} diff --git a/src/main/java/net/minecraftforge/fml/network/simple/SimpleChannel.java b/src/main/java/net/minecraftforge/fml/network/simple/SimpleChannel.java index d483da87f..79dfc6296 100644 --- a/src/main/java/net/minecraftforge/fml/network/simple/SimpleChannel.java +++ b/src/main/java/net/minecraftforge/fml/network/simple/SimpleChannel.java @@ -19,12 +19,11 @@ package net.minecraftforge.fml.network.simple; -import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.client.Minecraft; -import net.minecraft.network.NetworkManager; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.CPacketCustomPayload; +import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.fml.network.NetworkInstance; import java.util.function.BiConsumer; @@ -40,24 +39,18 @@ public class SimpleChannel { this.instance = instance; this.indexedCodec = new IndexedMessageCodec(); - instance.addListener(this::serverEventListener); - instance.addListener(this::clientEventListener); + instance.addListener(this::networkEventListener); } - private void clientEventListener(final NetworkInstance.NetworkEvent.ClientCustomPayloadEvent clientCustomPayloadEvent) + private void networkEventListener(final NetworkEvent networkEvent) { - } - - private void serverEventListener(final NetworkInstance.NetworkEvent.ServerCustomPayloadEvent serverCustomPayloadEvent) - { - this.indexedCodec.consume(serverCustomPayloadEvent.getPayload(), - ()->new MessageContext(serverCustomPayloadEvent.getSource(), NetworkInstance.NetworkSide.PLAYSERVER)); + this.indexedCodec.consume(networkEvent.getPayload(),networkEvent.getSource()); } public void encodeMessage(MSG message, final PacketBuffer target) { this.indexedCodec.build(message, target); } - public void registerMessage(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { + public void registerMessage(int index, Class messageType, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { this.indexedCodec.addCodecIndex(index, messageType, encoder, decoder, messageConsumer); } diff --git a/src/test/java/net/minecraftforge/debug/item/MapDataTest.java b/src/test/java/net/minecraftforge/debug/item/MapDataTest.java index e0b5150ac..45a213d97 100644 --- a/src/test/java/net/minecraftforge/debug/item/MapDataTest.java +++ b/src/test/java/net/minecraftforge/debug/item/MapDataTest.java @@ -51,7 +51,7 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.network.simple.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.GameRegistry; @@ -237,7 +237,7 @@ public class MapDataTest { @Nullable @Override - public IMessage onMessage(CustomMapPacket message, MessageContext ctx) + public IMessage onMessage(CustomMapPacket message, NetworkEvent.Context ctx) { // Like NetHandlerPlayClient.handleMaps but using our custom type Minecraft.getMinecraft().addScheduledTask(new Runnable() { diff --git a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler1.java b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler1.java index 9dfff552d..cdb360fde 100644 --- a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler1.java +++ b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler1.java @@ -20,12 +20,12 @@ package net.minecraftforge.fml.test.simplenet; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.network.simple.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; public class SimpleNetHandler1 implements IMessageHandler { @Override - public SimpleNetTestMessage2 onMessage(SimpleNetTestMessage1 message, MessageContext context) + public SimpleNetTestMessage2 onMessage(SimpleNetTestMessage1 message, NetworkEvent.Context context) { return null; } diff --git a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler2.java b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler2.java index 804e640b7..edbc3d24b 100644 --- a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler2.java +++ b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetHandler2.java @@ -20,12 +20,12 @@ package net.minecraftforge.fml.test.simplenet; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.network.simple.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; public class SimpleNetHandler2 implements IMessageHandler { @Override - public SimpleNetTestMessage1 onMessage(SimpleNetTestMessage2 message, MessageContext context) + public SimpleNetTestMessage1 onMessage(SimpleNetTestMessage2 message, NetworkEvent.Context context) { return null; }