Skip to content

Tutorial Receiving and sending opcodes

Joao Pasqualini Costa edited this page Jan 18, 2024 · 12 revisions

============= CLIENT

  1. Receiving custom opcode from the server

First go to:

/modules/gamelib/const.lua

Search for

ExtendedIds = {
    Activate = 0,
    Locale = 1,
    Ping = 2,
    Sound = 3,
    Game = 4,
    Particles = 5,
    MapShader = 6,
    NeedsUpdate = 7
}

Add your custom extended opcode there (can't be greater than 255):

ExtendedIds = {
    Activate = 0,
    Locale = 1,
    Ping = 2,
    Sound = 3,
    Game = 4,
    Particles = 5,
    MapShader = 6,
    NeedsUpdate = 7,

    MyCustomOpcode = 100,
}

Now on your module add the proper register and unregister method

function init()
    ProtocolGame.registerExtendedOpcode(ExtendedIds.MyCustomOpcode, onExtendedOpcode)
end

function terminate()
    ProtocolGame.unregisterExtendedOpcode(ExtendedIds.MyCustomOpcode)
end

function onExtendedOpcode(protocol, opcode, buffer)
    -- the client received some data from the server, print it
    print("Received data: ", buffer)
end
  1. Sending custom opcodes to the server

On your module add this function to send some data to the server

function sendOpcode(someData)
    local protocolGame = g_game.getProtocolGame()
    if protocolGame then
        -- Sending data to the server, print it
        print("Sending data: ", someData)
        protocolGame:sendExtendedOpcode(ExtendedIds.MyCustomOpcode, someData)
        return true
    end
    return false
end

============= CLIENT

NOTE: Tested in Canary 1.x

You will need to register the event in login.lua. In the function login.onLogin(player) look for:

    -- Events
    player:registerEvent("PlayerDeath")
    player:registerEvent("DropLoot")
    player:registerEvent("BossParticipation")

Resgister the extended opcode event there:

    -- Events
    player:registerEvent("PlayerDeath")
    player:registerEvent("DropLoot")
    player:registerEvent("BossParticipation")
    player:registerEvent('ExtendedOpcode') -- this

In creaturescripts\extended_opcode.lua put: player:sendExtendedOpcode(MyCustomOpcode, SomeData) It should look like this:

local OPCODE_LANGUAGE = 1
local OPCODE_MY_CUSTOM_OPCODE = 100

local extendedOpcode = CreatureEvent("ExtendedOpcode")

function extendedOpcode.onExtendedOpcode(player, opcode, buffer)
    if opcode == OPCODE_LANGUAGE then
        -- otclient language
        if buffer == "en" or buffer == "pt" then
            -- example, setting player language, because otclient is multi-language...
            -- player:setStorageValue(SOME_STORAGE_ID, SOME_VALUE)
        end
    elseif opcode == OPCODE_MY_CUSTOM_OPCODE then
        player:sendExtendedOpcode(OPCODE_MY_CUSTOM_OPCODE, 'SomeData')
    else
        -- other opcodes can be ignored, and the server will just work fine...
    end
end

extendedOpcode:register()