A much more straightforward networking system.

This commit is contained in:
cpw 2018-06-22 14:38:53 -04:00 committed by LexManos
parent 4636365e30
commit 506b51f189
18 changed files with 264 additions and 200 deletions

View file

@ -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<UUID, String> map = Maps.newHashMap();
private static Map<UUID, String> 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<Map<UUID, String>>() { private static final long serialVersionUID = 1L; }.getType();
map = gson.fromJson(json, type);
Type type = new TypeToken<Map<UUID, String>>(){}.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<>();
}
}
}

View file

@ -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;

View file

@ -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<REQ extends IMessage, REPLY extends IMessage> {
* @param message The message
* @return an optional return message
*/
REPLY onMessage(REQ message, MessageContext ctx);
REPLY onMessage(REQ message, NetworkEvent.Context ctx);
}

View file

@ -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<REQ extends IMessage, REPLY extends IMe
protected void channelRead0(ChannelHandlerContext ctx, REQ msg) throws Exception
{
INetHandler iNetHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
MessageContext context = new MessageContext(iNetHandler, side);
NetworkEvent.Context context = new NetworkEvent.Context(iNetHandler, side);
REPLY result = messageHandler.onMessage(msg, context);
if (result != null)
{

View file

@ -80,14 +80,14 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
* }
* // Message1Handler expects input of type Message1 and returns type Message2
* public Message1Handler implements IMessageHandler<Message1,Message2> {
* 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<Message2,IMessage> {
* 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;

View file

@ -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<String> 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;
}
}

View file

@ -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<PacketBuffer, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier;
Network(BiFunction<PacketBuffer, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier)
{
this.eventSupplier = eventSupplier;
}
public NetworkEvent getEvent(final PacketBuffer buffer, final Supplier<NetworkEvent.Context> manager) {
return this.eventSupplier.apply(buffer, manager);
}
}

View file

@ -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<Context> source;
private NetworkEvent(PacketBuffer payload, Supplier<Context> source)
{
this.payload = payload;
this.source = source;
}
public PacketBuffer getPayload()
{
return payload;
}
public Supplier<Context> getSource()
{
return source;
}
public static class ServerCustomPayloadEvent extends NetworkEvent
{
ServerCustomPayloadEvent(final PacketBuffer payload, final Supplier<Context> source) {
super(payload, source);
}
}
public static class ClientCustomPayloadEvent extends NetworkEvent
{
ClientCustomPayloadEvent(final PacketBuffer payload, final Supplier<Context> 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;
}
}
}

View file

@ -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)

View file

@ -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<PacketBuffer, NetworkManager, NetworkEvent> eventSupplier;
NetworkSide(BiFunction<PacketBuffer, NetworkManager, NetworkEvent> 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<String> networkProtocolVersion;
private final Predicate<String> clientAcceptedVersions;
@ -76,9 +57,9 @@ public class NetworkInstance
}
public <T extends NetworkEvent> void addListener(Consumer<T> serverEventListener)
public <T extends NetworkEvent> void addListener(Consumer<T> 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);
}
}
}
}

View file

@ -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<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) {
return new SimpleChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions));
}
public static EventNetworkChannel newEventChannel(final ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) {
return new EventNetworkChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions));
}
private static NetworkInstance createInstance(ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> 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<NetworkInstance> findTarget(ResourceLocation resourceLocation)

View file

@ -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 <T extends NetworkEvent> void addListener(Consumer<T> eventListener)
{
instance.addListener(eventListener);
}
public void registerObject(Object object)
{
instance.registerObject(object);
}
public void unregisterObject(Object object)
{
instance.unregisterObject(object);
}
}

View file

@ -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<BiConsumer<MSG, PacketBuffer>> encoder;
private final Optional<Function<PacketBuffer, MSG>> decoder;
private final int index;
private final BiConsumer<MSG,Supplier<MessageContext>> messageConsumer;
private final BiConsumer<MSG,Supplier<NetworkEvent.Context>> messageConsumer;
private final Class<MSG> messageType;
public CodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer)
public CodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer)
{
this.index = index;
this.messageType = messageType;
@ -61,13 +62,16 @@ public class IndexedMessageCodec
}
private static <M> void tryDecode(PacketBuffer payload, Supplier<MessageContext> context, CodecIndex<M> codec)
private static <M> void tryDecode(PacketBuffer payload, Supplier<NetworkEvent.Context> context, CodecIndex<M> codec)
{
codec.decoder.map(d->d.apply(payload)).ifPresent(m->codec.messageConsumer.accept(m, context));
}
private static <M> void tryEncode(PacketBuffer target, M message, CodecIndex<M> codec) {
codec.encoder.ifPresent(c->c.accept(message, target));
codec.encoder.ifPresent(encoder->{
target.writeByte(codec.index & 0xff);
encoder.accept(message, target);
});
}
public <MSG> void build(MSG message, PacketBuffer target)
{
@ -80,7 +84,7 @@ public class IndexedMessageCodec
tryEncode(target, message, codecIndex);
}
void consume(final PacketBuffer payload, Supplier<MessageContext> context) {
void consume(final PacketBuffer payload, Supplier<NetworkEvent.Context> 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);
}
<MSG> void addCodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer) {
<MSG> void addCodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer) {
new CodecIndex<>(index, messageType, encoder, decoder, messageConsumer);
}
}

View file

@ -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;
}
}

View file

@ -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 <MSG> void encodeMessage(MSG message, final PacketBuffer target) {
this.indexedCodec.build(message, target);
}
public <MSG> void registerMessage(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer) {
public <MSG> void registerMessage(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer) {
this.indexedCodec.addCodecIndex(index, messageType, encoder, decoder, messageConsumer);
}

View file

@ -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() {

View file

@ -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<SimpleNetTestMessage1, SimpleNetTestMessage2>
{
@Override
public SimpleNetTestMessage2 onMessage(SimpleNetTestMessage1 message, MessageContext context)
public SimpleNetTestMessage2 onMessage(SimpleNetTestMessage1 message, NetworkEvent.Context context)
{
return null;
}

View file

@ -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<SimpleNetTestMessage2, SimpleNetTestMessage1>
{
@Override
public SimpleNetTestMessage1 onMessage(SimpleNetTestMessage2 message, MessageContext context)
public SimpleNetTestMessage1 onMessage(SimpleNetTestMessage2 message, NetworkEvent.Context context)
{
return null;
}