Skip to main content

Overview

The ClientConnection class manages the client-side network connection to a Minecraft server. It handles packet processing, level synchronization, and player state management for multiplayer gameplay.

Class Definition

class ClientConnection : public PacketListener
Location: Minecraft.Client/ClientConnection.h

Constructor

ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex = -1)

Parameters

  • minecraft - Pointer to the main Minecraft instance
  • socket - Network socket for communication (NULL for local connection)
  • iUserIndex - User index for the connection (defaults to primary pad if -1)

Connection Lifecycle

Connection States

The client connection progresses through several states during initialization:
enum eClientConnectionConnectingState
{
    eCCPreLoginSent = 0,
    eCCPreLoginReceived,
    eCCLoginSent,
    eCCLoginReceived,
    eCCConnected
};

State Management Methods

tick()

void tick()
Processes incoming packets and flushes outgoing data. Call this every game tick to maintain the connection. Example:
if (!clientConnection->isClosed()) {
    clientConnection->tick();
}

close()

void close()
Cleanly closes the connection and releases resources.

isStarted()

bool isStarted()
Returns true if the connection has completed initialization and gameplay has started.

isClosed()

bool isClosed()
Returns true if the connection has been closed or disconnected.

Sending Packets

send()

void send(shared_ptr<Packet> packet)
Sends a packet to the server. Example:
// Send a chat message
auto chatPacket = make_shared<ChatPacket>(L"Hello, world!");
clientConnection->send(chatPacket);

// Send player movement
auto movePacket = make_shared<MovePlayerPacket::PosRot>(
    player->x, player->y, player->yView, player->z,
    player->yRot, player->xRot, player->onGround, player->isFlying
);
clientConnection->send(movePacket);

sendAndDisconnect()

void sendAndDisconnect(shared_ptr<Packet> packet)
Sends a packet and then gracefully disconnects from the server.

Handling Disconnects

handleDisconnect()

virtual void handleDisconnect(shared_ptr<DisconnectPacket> packet)
Processes a disconnect packet received from the server. See DisconnectPacket.h:10 for disconnect reasons.

onDisconnect()

virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects)
Called when the connection is lost or terminated. Common Disconnect Reasons:
  • eDisconnect_Quitting - Player chose to quit
  • eDisconnect_Closed - Connection closed normally
  • eDisconnect_TimeOut - Connection timed out
  • eDisconnect_ServerFull - Server has reached max players
  • eDisconnect_OutdatedClient - Client version is incompatible
  • eDisconnect_Kicked - Player was kicked by server
Example:
void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) {
    if (reason == DisconnectPacket::eDisconnect_TimeOut) {
        // Show timeout message to user
    } else if (reason == DisconnectPacket::eDisconnect_Kicked) {
        // Show kicked message
    }
    // Cleanup and return to main menu
}

Packet Handlers

The ClientConnection class implements handlers for all client-received packets. Key handlers include:

Login and Setup

handleLogin()

virtual void handleLogin(shared_ptr<LoginPacket> packet)
Processes the login response from the server, initializes the level, and sets up the local player.
  • Sets player entity ID and dimension
  • Creates the multiplayer level
  • Initializes game mode
  • Configures player privileges and settings
See ClientConnection.cpp:158 for full implementation.

Entity Management

handleAddEntity()

virtual void handleAddEntity(shared_ptr<AddEntityPacket> packet)
Spawns a new entity in the world (boats, minecarts, projectiles, etc.). See ClientConnection.cpp:411.

handleAddPlayer()

virtual void handleAddPlayer(shared_ptr<AddPlayerPacket> packet)
Adds a remote player to the world. See ClientConnection.cpp:726.

handleRemoveEntity()

virtual void handleRemoveEntity(shared_ptr<RemoveEntitiesPacket> packet)
Removes entities from the world when they’re destroyed.

Movement and Animation

handleTeleportEntity()

virtual void handleTeleportEntity(shared_ptr<TeleportEntityPacket> packet)
Teleports an entity to a new position with rotation.

handleMoveEntity()

virtual void handleMoveEntity(shared_ptr<MoveEntityPacket> packet)
Updates entity position with relative movement.

handleMovePlayer()

virtual void handleMovePlayer(shared_ptr<MovePlayerPacket> packet)
Processes server-side player position corrections. See ClientConnection.cpp:961.

World Updates

handleChunkVisibility()

virtual void handleChunkVisibility(shared_ptr<ChunkVisibilityPacket> packet)
Updates chunk visibility state for level of detail management.

handleTileUpdate()

virtual void handleTileUpdate(shared_ptr<TileUpdatePacket> packet)
Updates a single block in the world. See ClientConnection.cpp:1137.

handleChunkTilesUpdate()

virtual void handleChunkTilesUpdate(shared_ptr<ChunkTilesUpdatePacket> packet)
Updates multiple blocks in a chunk efficiently.

Gameplay Events

handleChat()

virtual void handleChat(shared_ptr<ChatPacket> packet)
Processes chat messages and localized game events. See ClientConnection.cpp:1328.

handleSetHealth()

virtual void handleSetHealth(shared_ptr<SetHealthPacket> packet)
Updates local player health from server.

handleRespawn()

virtual void handleRespawn(shared_ptr<RespawnPacket> packet)
Handles player respawn after death.

Properties

Connection State

bool done;              // Connection has closed
bool createdOk;         // Socket creation succeeded
bool started;           // Gameplay has started
Connection *connection; // Underlying network connection

Game State

MultiPlayerLevel *level;           // The multiplayer level
Minecraft *minecraft;              // Main game instance
int maxPlayers;                    // Maximum players on server
SavedDataStorage *savedDataStorage; // Shared saved data

Network Player

getNetworkPlayer()

INetworkPlayer *getNetworkPlayer()
Returns the network player interface for this connection, or NULL if unavailable.

getSocket()

Socket *getSocket()
Returns the underlying socket for platform-specific network operations.

Best Practices

  1. Always check createdOk after construction before using the connection
  2. Call tick() every frame while the connection is active
  3. Handle disconnects gracefully to provide good user experience
  4. Don’t send packets before login completes - wait for started to be true
  5. Clean up resources by calling close() when done

Thread Safety

The ClientConnection class processes packets on the network thread but updates game state on the main thread. The tick() method should only be called from the main game thread.

See Also

Build docs developers (and LLMs) love