Skip to content

Create a packet handler

虎視ぞ edited this page Apr 2, 2023 · 1 revision

Create a packet handler

Now that you have your packet, you might want to handle actions with it. For this guide we will do a ClientPacketHandler, but that's basically the same principle for the ServerPacketHandler.

  • From this point, I will assume you are in the protocol/client/packets directory*

1. Create a PacketHandler that inherits from the ClientPacketHandler class:

#pragma once

#include "../ClientPacketHandler.hpp"

namespace babel {

    class PacketNamePacketHandler: public ClientPacketHandler {
        public:
            const void handle(Packet &packet, std::shared_ptr<ClientManager> clientManager) const override;
    };
    
}

2. Next thing, we have to implement the class:

#include "PacketNamePacketHandler.hpp"
#include "../../packets/PacketName.hpp"
#include "../../../client/ClientManager.hpp"

using namespace babel;

const void PacketNamePacketHandler::handle(Packet &packet, std::shared_ptr<ClientManager> clientManager) const {
    try {
        PacketName &packetNamePacket = dynamic_cast<PacketName&>(packet);
        // Do your actions below, you have access to the clientManager variable so you can basically process whatever actions you want.
    } catch (std::bad_cast) {}
}

3. Last thing, we have to register the handler in our ClientPacketManager

../ClientPacketManager.cpp

// ... Other includes above
#include "packets/PacketNamePacketHandler.hpp"

using namespace babel;

ClientPacketManager::ClientPacketManager(std::shared_ptr<ClientManager> clientManager) {
    this->_clientManager = clientManager;

    // ...
    this->registerHandler(PacketType::YOUR_PACKET_TYPE, std::shared_ptr<ClientPacketHandler>(new PacketNamePacketHandler()));
}
That's it !
With the current client's implementation, the handler will be automatically called if sent by the server !

Clone this wiki locally