Created initial Network class with version checking.

This commit is contained in:
2022-01-16 13:08:24 +00:00
parent 78636c242d
commit bb455e3d44

View File

@ -0,0 +1,62 @@
package dev.micle.totemofreviving.network;
import dev.micle.totemofreviving.TotemOfReviving;
import dev.micle.totemofreviving.util.MismatchedVersionException;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import java.util.Objects;
import java.util.regex.Pattern;
public class Network {
public static final String VERSION = TotemOfReviving.MOD_ID + "-net-1";
private static final Pattern NET_VERSION_PATTERN = Pattern.compile(TotemOfReviving.MOD_ID + "-net-\\d+$");
private static final Pattern MOD_VERSION_PATTERN = Pattern.compile("^\\d+\\.\\d+\\.\\d+$");
public static SimpleChannel channel;
public static void init() {
channel = NetworkRegistry.ChannelBuilder.named(TotemOfReviving.createResourceLocation("network"))
.clientAcceptedVersions(s -> Objects.equals(s, VERSION))
.serverAcceptedVersions(s -> Objects.equals(s, VERSION))
.networkProtocolVersion(() -> VERSION)
.simpleChannel();
}
public static void writeVersionInfo(PacketBuffer buffer) {
buffer.writeUtf(VERSION);
buffer.writeUtf(TotemOfReviving.getVersion());
}
public static void checkVersion(PacketBuffer buffer) {
String serverNetVersion = readNetVersion(buffer);
String serverModVersion = readModVersion(buffer);
if (!VERSION.equals(serverNetVersion) || !TotemOfReviving.getVersion().equals(serverModVersion)) {
throw new MismatchedVersionException(
String.format("The server and client are running different versions of [Micle's Totem of Reviving]." +
"Try updating this mod on either the client and or the server." +
"Client version is %s (%s). Server version is %s (%s)",
TotemOfReviving.getVersion(), VERSION,
serverModVersion, serverNetVersion)
);
}
}
public static String readNetVersion(PacketBuffer buffer) {
String netVersion = buffer.readUtf(16);
if (!NET_VERSION_PATTERN.matcher(netVersion).matches()) {
return "UNKNOWN (" + netVersion + ")";
}
return netVersion;
}
public static String readModVersion(PacketBuffer buffer) {
String modVersion = buffer.readUtf(16);
if (!MOD_VERSION_PATTERN.matcher(modVersion).matches()) {
return "UNKNOWN (" + modVersion + ")";
}
return modVersion;
}
}