Handling Packets

LibMinecraft allows you to override its default logic for any packet. There are two event handlers involved in this process: MultiplayerServer.PrePacket and MultiplayerServer.PostPacket.  If you use the first event handler, you are also to override each packet's logic.  If you override the latter, you are only able to run custom logic only after LibMinecraft has completed its handling of each packet.  In this example, we'll override the Chat packet and stop it from notifying other players of the chat.

Note: You can find good documentation of the Minecraft protocol and packet format here: http://wiki.vg/Protocol

In your server, you can add an event handler to PrePacket like so:

Code (C#): Register for the event handler

multiplayerServer.PrePacket += new EventHandler<PacketEventArgs>(PrePacketHandler);

Here's a method for handling chat update packets:

Code (C#): Packet handler

private void PrePacketHandler(object sender, PacketEventArgs e)
	if (e.PacketID != PacketID.ChatUpdate)
	// Set this to prevent LibMinecraft from handling the packet
	e.Handled = true;
	// You must call this, even if you don't have any
	// special packet handling, as long as e.Handled is true.
	e.Packet.ReadPacket(multiplayerServer, e.RemoteClient);
	Console.WriteLine("Prevented LibMinecraft from sending chat: " +
				      (e.Packet as ChatMessagePacket).Message);

Note that if you set e.Handled to true, you must use e.Packet.ReadPacket to read in the contents of the packet.  Otherwise, the contents of the packet will be interpreted as another packet, and likely cause many errors.

Last edited Feb 24, 2012 at 10:25 PM by sircmpwn, version 4


No comments yet.