Created
November 21, 2012 05:43
-
-
Save aadnk/4123276 to your computer and use it in GitHub Desktop.
Using the new synchronous client packet listeners
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.comphenix.example; | |
import org.bukkit.command.Command; | |
import org.bukkit.command.CommandSender; | |
import org.bukkit.entity.Player; | |
import org.bukkit.event.Listener; | |
import org.bukkit.plugin.java.JavaPlugin; | |
import com.comphenix.protocol.Packets; | |
import com.comphenix.protocol.ProtocolLibrary; | |
import com.comphenix.protocol.ProtocolManager; | |
import com.comphenix.protocol.events.ConnectionSide; | |
import com.comphenix.protocol.events.PacketAdapter; | |
import com.comphenix.protocol.events.PacketEvent; | |
import com.comphenix.protocol.reflect.FieldAccessException; | |
public class SynchronousCensor extends JavaPlugin implements Listener { | |
private static final int TICKS_PER_SECOND = 20; | |
private ProtocolManager manager; | |
public void onLoad() { | |
manager = ProtocolLibrary.getProtocolManager(); | |
} | |
@Override | |
public void onEnable() { | |
final Thread mainThread = Thread.currentThread(); | |
manager.getAsynchronousManager().registerAsyncHandler( | |
new PacketAdapter(this, ConnectionSide.CLIENT_SIDE, Packets.Client.CHAT) { | |
@Override | |
public void onPacketReceiving(final PacketEvent event) { | |
try { | |
// Proof that we're running on the main thread | |
if (Thread.currentThread().getId() == mainThread.getId()) { | |
if (!event.getPlayer().hasPermission("chat.offensive")) { | |
String message = event.getPacket().getStrings().read(0); | |
if (message.contains("shit") || message.contains("fuck")) { | |
event.getPlayer().sendMessage("Bad manners!"); | |
event.setCancelled(true); | |
} | |
} | |
// Add a delay of 2 seconds | |
if (!event.isCancelled()) { | |
event.getAsyncMarker().incrementProcessingDelay(); | |
getServer().getScheduler().scheduleSyncDelayedTask(ExampleMod.this, new Runnable() { | |
@Override | |
public void run() { | |
manager.getAsynchronousManager().signalPacketTransmission(event); | |
} | |
}, TICKS_PER_SECOND * 2); | |
} | |
System.out.println("Processed on the main thread. Cancelled: " + event.isCancelled()); | |
} else { | |
System.out.println("Something bad happened."); | |
} | |
} catch (FieldAccessException e) { | |
// Error | |
e.printStackTrace(); | |
} | |
} | |
// Remember this! | |
}).syncStart(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment