I expect that you only want to drop packets that the game is responsible for, and not all of your own network traffic on the local machine. With this in mind, it depends on the game and what messaging protocol they use.
Lets say the game is Minecraft. There's a popular new tech solution being used to write mods called
Mixins. What most people will do is write a mixin that allows them to inject code into the networking logic that effectively just calls
"return;" You could write them in such a way that it only does this when a key is pressed, or if the packet only contains some sort of specific data. Now, Minecraft has things like
FabricMC which makes this rather complicated task relatively easy. The same thing can be done for
any java application with enough effort, just Minecraft has most of the development cycle already made for you.
Continuing with the Minecraft example, lets say setting up that developer workspace is too much. You can still edit the compiled game classes with
a bytecode editor. It would be effectively the same thing as described above, but you'd hard-code that logic into the game by inserting additional bytecode. You'd navigate to the networking class, then insert some logic like:
Code
void sendPacket(Packet p) {
if (isMyKeyDown()) {
return;
}
...
}
Where
"isMyKeyDown()" would be defined somewhere that has access to the keyboard states. Minecraft uses LWJGL 3, so there's callbacks that it registers for handling user inputs. I imagine most other games follow a similar design, so you'd have to hook some logic in there to track if the key you want is pressed. Its a hacky approach but should do the job.
Another way, if the game easily provides the networking libraries it uses in a way that is easy to swap out, you can clone the source of it from GitHub assuming its something like Netty, then find where packets are sent, and add your keyboard hook in there. Compile to jar, swap out with what the game provides. Another hacky approach but also works.
Having a system level packet hook would be out of scope for Java really, and probably a bit unwieldy to make it automatically know what packets you want dropped.