Get realtime online users and running matches

@renhades ,
Answer 1 : Here’s one way that we use for our game.
We have created custom stream for that purpose and upon successful authentication, user’s join that stream, and then we count the presences on that stream to get online players count. Also note that, whenever user disconnects from server, it’s removed from the streams too by default.
You can read more about them here - https://heroiclabs.com/docs/advanced-streams/.

Here’s a sample(assuming you are using Lua) -

local nk = require("nakama")

local stream_model = {}

stream_model.streams = {
    online_stream_id = {
        mode = 1000
    }
}

function stream_model.close_stream(stream_id)
    log.log_norm("[stream_model/close_stream] : closing stream" .. nk.json_encode(stream_id))

    nk.stream_close(stream_id)
end

function stream_model.join_stream(user_id, session_id, stream_id, hidden, persistence)
    --nk.logger_info("[stream_model/join_stream] : User " .. user_id .. " is joining stream = " .. nk.json_encode(stream_id))

    nk.stream_user_join(user_id, session_id, stream_id, hidden, persistence)
end

function stream_model.leave_stream(user_id, session_id, stream_id)
    --nk.logger_info("[stream_model/leave_stream] : User " .. user_id .. " is leaving stream = " .. nk.json_encode(stream_id))

    nk.stream_user_leave(user_id, session_id, stream_id)
end

function stream_model.count_users_on_stream(stream_id)
    local count = nk.stream_count(stream_id)

    --nk.logger_info("[stream_model/count_users_on_stream] : counting users on stream ".. nk.json_encode(stream_id) ..". Count = " .. count)

    return count
end

And then you could do something like this with an RPC call - to add user to that stream

function join_online_users_stream(context, _)
    --nk.logger_info("[join_online_users_stream] : User is joining online users stream = " .. context.username)

    local hidden = true
    local persistence = false
    stream_model.join_stream(context.user_id, context.session_id, stream_model.streams.online_stream_id, hidden, persistence)
end

And use this to get count of online players -

function count_users_on_online_users_stream()
    local count = stream_model.count_users_on_stream(stream_model.streams.online_stream_id)

    --nk.logger_info("[count_users_on_online_users_stream] : Count of online users = " .. count)

    return count
end
4 Likes