我通过 Bukkit 插件发送数据包。包裹发送代码:
try {
String full_msg = "Text(" + message + ")";
byte[] data = full_msg.getBytes(StandardCharsets.UTF_8);
MinecraftKey channel = new MinecraftKey("chilove", "main");
PacketContainer packet = new PacketContainer(PacketType.Play.Server.CUSTOM_PAYLOAD);
packet.getMinecraftKeys().write(0, channel);
ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
Object serializer = MinecraftReflection.getPacketDataSerializer(byteBuf);
packet.getModifier().withType(ByteBuf.class).write(0, serializer);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
return true;
} catch (Exception exception) {
Bukkit.getLogger().info(ConsoleColor.ANSI_RED + "Error on TextPacket: " + ConsoleColor.ANSI_CYAN + " (" + exception.getMessage() + ")" + ConsoleColor.ANSI_RESET);
exception.printStackTrace();
}
return false;
}
数据包本身是无条件发送的...但是 mod 上的处理程序根本不起作用。尝试创建处理程序的代码是:
private static final String PROTOCOL_VERSION = "1";
public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(
new ResourceLocation("chilove", "main"),
() -> PROTOCOL_VERSION,
PROTOCOL_VERSION::equals,
PROTOCOL_VERSION::equals
);
public static void register() {
// INSTANCE.registerMessage(0, TextPacket.class, TextPacket::encode, TextPacket::decode, TextPacket::handle);
int id = 0;
INSTANCE.messageBuilder(TextPacket.class, id++, NetworkDirection.PLAY_TO_SERVER)
.decoder(TextPacket::decode)
.consumerMainThread(TextPacket::handle)
.add();
INSTANCE.registerMessage(id++, TextPacket.class, TextPacket::encode, TextPacket::decode, TextPacket::handle);
INSTANCE.messageBuilder(TextPacket.class, id++, NetworkDirection.PLAY_TO_CLIENT)
.decoder(TextPacket::decode)
.consumerMainThread(TextPacket::handle)
.add();
}
TextPacket.class:
public class TextPacket {
private String text;
public TextPacket() { }
public TextPacket(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static TextPacket decode(FriendlyByteBuf buffer) {
byte[] bytes = buffer.readByteArray();
String text = new String(bytes, StandardCharsets.UTF_8);
ChiloveMod.LOGGER.info("Decoded text: {}", text);
return new TextPacket(text);
}
public void encode(FriendlyByteBuf buffer) {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
buffer.writeByteArray(bytes);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
ChiloveMod.LOGGER.info("Received message: {}", text);
});
ctx.get().setPacketHandled(true);
}
}
我尝试了很多选项,并在互联网上搜索了有关 SimpleImpl 的所有信息。通常,当发送数据包时,我会在控制台中收到 2 个错误:
尝试通过 ClientboundCustomPayloadEvent 等事件。
sendPluginMessage(plugin, channel, data)
Player p = ...;
String full_msg = "Text(" + message + ")";
byte[] data = full_msg.getBytes(StandardCharsets.UTF_8);
p.sendPluginMessage(MyPlugin.getInstance(), "chilove:main", data);
论据是:
project:name
。如果您使用
new MinecraftKey("a", "b")
创建密钥,那么通道将为
a:b