Skip to main content

Overview

The ServerConnection class manages all network connections on the server side. It handles incoming connections, player management, and distributes packets to connected clients.

Class Definition

class ServerConnection
Location: Minecraft.Client/ServerConnection.h

Constructor

ServerConnection(MinecraftServer *server)

Parameters

  • server - Pointer to the MinecraftServer instance that owns this connection manager
Example:
MinecraftServer *server = new MinecraftServer();
ServerConnection *serverConnection = new ServerConnection(server);

Connection Management

Accepting Connections

NewIncomingSocket()

void NewIncomingSocket(Socket *socket)
Accepts a new incoming client connection. Creates a PendingConnection to handle the login process. Example:
// When a new client connects
Socket *clientSocket = acceptNewConnection();
serverConnection->NewIncomingSocket(clientSocket);
Implementation Details:
  • Creates a PendingConnection for the handshake phase
  • Assigns a unique connection ID
  • Adds to pending connections list for processing
See ServerConnection.cpp:27 for implementation.

Player Connection Management

addPlayerConnection()

void addPlayerConnection(shared_ptr<PlayerConnection> playerConnection)
Promotes a pending connection to a full player connection after successful login. Example:
// After login is validated
auto playerConnection = make_shared<PlayerConnection>(server, connection, player);
serverConnection->addPlayerConnection(playerConnection);

Connection Lifecycle

tick()

void tick()
Processes all connections each game tick. This method:
  1. Ticks all pending connections (login phase)
  2. Removes completed pending connections
  3. Ticks all active player connections
  4. Handles chunk sending for players
  5. Removes disconnected players
  6. Flushes network buffers
Example:
// In server main loop
while (serverRunning) {
    serverConnection->tick();
    // ... other server logic
}
See ServerConnection.cpp:62 for implementation.

stop()

void stop()
Disconnects all players and closes all connections gracefully. Example:
// When shutting down server
serverConnection->stop();

Player Connection List

Connection Storage

vector<shared_ptr<PendingConnection>> pending;  // Connections in login phase
vector<shared_ptr<PlayerConnection>> players;   // Active player connections
Both lists are protected by critical sections for thread safety.

Thread Safety

CRITICAL_SECTION pending_cs;  // Protects pending connections list
The pending_cs critical section ensures thread-safe access when accepting new connections from the network thread.

Network Player Interface

Player States

Connections progress through these states:
  1. Socket Accepted - Network connection established
  2. Pending Connection - Handshake and login phase
  3. Player Connection - Authenticated and in-game
  4. Disconnected - Connection closed

Connection Flow

NewIncomingSocket()

PendingConnection created

handleConnection()

Login validation

addPlayerConnection()

PlayerConnection active

tick() processing

Disconnect / Remove

Texture Synchronization

The server handles custom texture/skin requests from clients:

addPendingTextureRequest()

bool addPendingTextureRequest(const wstring &textureName)
Queues a texture request. Returns true if the request should be sent. Example:
if (serverConnection->addPendingTextureRequest(L"custom_skin_123")) {
    // Request texture from clients
}

handleTextureReceived()

void handleTextureReceived(const wstring &textureName)
Processes a received texture and distributes it to players who need it. Example:
// When texture data arrives
serverConnection->handleTextureReceived(textureName);
// Texture is now forwarded to waiting players
See ServerConnection.cpp:132 for implementation.

handleTextureAndGeometryReceived()

void handleTextureAndGeometryReceived(const wstring &textureName)
Handles combined texture and geometry data (for custom player models).

Server Settings

handleServerSettingsChanged()

void handleServerSettingsChanged(shared_ptr<ServerSettingsChangedPacket> packet)
Broadcasts server setting changes to all connected clients. Settings Types:
  • HOST_DIFFICULTY - Game difficulty level
  • HOST_IN_GAME_SETTINGS - Various gameplay options
Example:
// Change server difficulty
auto settingsPacket = make_shared<ServerSettingsChangedPacket>(
    ServerSettingsChangedPacket::HOST_DIFFICULTY,
    newDifficulty
);
serverConnection->handleServerSettingsChanged(settingsPacket);
See ServerConnection.cpp:166 for implementation.

Properties

Server State

volatile bool running;        // Server is accepting connections
MinecraftServer *server;      // Owning server instance
int connectionCounter;        // Unique ID counter for connections

Pending Requests

vector<wstring> m_pendingTextureRequests;  // Textures being requested
Tracks which custom textures are currently being requested to avoid duplicates.

Spam Protection

removeSpamProtection()

void removeSpamProtection(Socket *socket)
Removes rate limiting for a trusted connection. Currently not implemented in Minecraft Community Edition.

Best Practices

1. Regular Ticking

Call tick() consistently every server frame:
// Server main loop
while (running) {
    serverConnection->tick();
    server->tick();
    Thread::sleep(50); // 20 TPS
}

2. Clean Shutdown

Always call stop() before destroying the server:
serverConnection->stop();
delete serverConnection;
delete server;

3. Connection Validation

Validate connections in the pending phase before promoting to player:
// In PendingConnection::handleLogin()
if (validatePlayerCredentials(packet)) {
    auto playerConnection = createPlayerConnection();
    serverConnection->addPlayerConnection(playerConnection);
}

4. Thread Safety

Always use the critical section when accessing pending connections from network threads:
EnterCriticalSection(&pending_cs);
// Access pending list
LeaveCriticalSection(&pending_cs);

Performance Considerations

Connection Limits

The server supports multiple simultaneous connections. Monitor the connection count:
int activePlayerCount = serverConnection->players.size();
int pendingCount = serverConnection->pending.size();

Bandwidth Management

  • Use PlayerConnection::queueSend() for non-critical packets
  • Batch multiple tile updates into ChunkTilesUpdatePacket
  • Limit texture synchronization frequency

Error Handling

The connection manager handles various error conditions:
  • Connection timeouts - Automatically disconnects inactive clients
  • Malformed packets - Validates and rejects invalid data
  • Resource limits - Can reject connections if server is full

See Also

Build docs developers (and LLMs) love