Sending Packets (Network) - MeAlam1/BlueLib GitHub Wiki
Sending Packets
Overview
Once you’ve registered your network packets using BlueLib’s packet system, the next step is to send them between the client and server. The NetworkRegistry
class provides a clean, centralized API to simplify packet transmission across different targets, including the server, individual players, or all connected players.
This page explains the available methods for sending packets and how to use them effectively.
Supported Packet Directions
BlueLib distinguishes between two primary packet directions:
- Client to Server (C2S): Sent from a client to the server.
- Server to Client (S2C): Sent from the server to one or more clients.
Sending Packets from the Client to the Server
To send a packet from the client to the server, use the following method:
NetworkRegistry.sendToServer(new MyPacket(...));
This should only be called from client-side code. The packet must be registered as a C2S packet or it will not be processed.
Sending Packets from the Server to a Player
To send a packet from the server to a specific player, use:
NetworkRegistry.sendPacket(ServerPlayer player, new MyPacket(...));
This internally routes through sendPacketToPlayer
, and is functionally identical. You can also use the method directly:
NetworkRegistry.sendPacketToPlayer(ServerPlayer player, new MyPacket(...));
This is ideal for responses, targeted updates, or personal messages to a specific player.
Sending Packets to All Players
To broadcast a packet from the server to all connected players, use:
NetworkRegistry.sendToAllPlayers(new MyPacket(...));
This will iterate through all players on the server and deliver the packet to each one individually.
Sending Packets to a Specific Group of Players
You can also target a specific group of players using:
NetworkRegistry.sendPacketToPlayers(Collection<ServerPlayer> players, new MyPacket(...));
This is useful for sending packets to players within a certain radius, team, or other filtered group.
Key Points
- Direction Matters: Always match your packet direction (C2S or S2C) to the appropriate sending method.
- Avoid Client-Side Calls: Do not call S2C send methods from the client—only the server should send packets to players.
- Efficient Broadcasting: Use
sendToAllPlayers
for global updates, but filter usingsendPacketToPlayers
when targeting specific groups.
Example Usage
// Send a packet to the server
NetworkRegistry.sendToServer(new TestPacket(...));
// Send a packet to a specific player
NetworkRegistry.sendPacket(player, new TestPacket(...));
// Broadcast to all players
NetworkRegistry.sendToAllPlayers(new TestPacket(...));
This API abstracts platform-specific implementation details, providing a clean and unified interface for all network communication. For help with writing custom packets and handlers, reach out in the official Discord community.