Skip to content

[DX L3] Typed message dispatcher #20

Description

@Segfaultd

Context

Message handling is a giant switch on the first byte, plus a hand-rolled helper to cope with the ID_TIMESTAMP prefix. From Chat Example Client.cpp:276-282 and :355-367:

for (p=client->Receive(); p; client->DeallocatePacket(p), p=client->Receive()) {
    packetIdentifier = GetPacketIdentifier(p);     // see below
    switch (packetIdentifier) { case ID_CONNECTION_REQUEST_ACCEPTED: ... }
}

unsigned char GetPacketIdentifier(MafiaNet::Packet *p) {
    if (p==0) return 255;
    if ((unsigned char)p->data[0] == ID_TIMESTAMP)
        return (unsigned char) p->data[sizeof(MafiaNet::MessageID) + sizeof(MafiaNet::Time)];
    return (unsigned char) p->data[0];
}

Custom messages are arithmetic on ID_USER_PACKET_ENUM (last enum in MessageIdentifiers.h), e.g. bsOut.Write((MessageID)(ID_USER_PACKET_ENUM+1)).

Goal

A typed dispatcher built on the receive iterator (#17) and archive (#19):

Dispatcher d;
d.on<ChatMessage>([](const ChatMessage& m, const Sender& from) { /* ... */ });
d.on(ID_NEW_INCOMING_CONNECTION, [](const Sender& s) { /* ... */ });

for (auto pkt : peer.incoming())
    d.dispatch(pkt);

Where

New header Source/include/mafianet/Dispatcher.h. Export from umbrella (#12).

Notes

  • on<T>() assigns the next ID from ID_USER_PACKET_ENUM; dispatch() reads the ID byte, skips the header (and the ID_TIMESTAMP+Time prefix exactly like GetPacketIdentifier above), constructs T, runs its serialize() ([DX L2] Serialization adapter over BitStream #19) in read mode, and invokes the handler.
  • Sender should expose guid() / address() using the optional/to_string helpers from [DX L0] Value-type fixes: thread-safe Guid::to_string, optional/string_view #15.
  • Keep the raw switch (pkt.id()) path fully usable — the dispatcher is opt-in sugar.
  • Decide how IDs stay in sync between peers (registration order must match, or expose explicit IDs) — document the contract.

Acceptance criteria

  • Round-trip: register ChatMessage, send it ([DX L3] Typed send/broadcast overloads #21), handler fires with equal fields.
  • ID_TIMESTAMP-prefixed packets dispatch to the correct handler.
  • System IDs (e.g. ID_NEW_INCOMING_CONNECTION) dispatch via on(id, ...).

Dependencies

Highest-leverage change — the thing that makes the library feel modern.

Metadata

Metadata

Assignees

No one assigned

    Labels

    dxDeveloper experience / public API ergonomicsenhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions