Server function on socket disconnect

Hello,

Is there anyway for the server to run a function (either Lua or Go) on client socket disconnect? I’d like to do some cleanup since players will be interacting with a third party service indirectly via RPC.

It’s not documented yet but you can register an event handler in the Go runtime that triggers when a session ends for any reason: connection lost, user disconnected and so on.

3 Likes

@zyro, just wondering, Is there any equivalent for this in Lua runtime?

No, there’s currently no Lua equivalent for the event functions. You can mix and match the runtimes, so use these Go-based functions alongside your existing Lua modules.

Hi any specific reason that the nk runtime.NakamaModule, db *sql.DB are not made available in this function?

Yes - we specifically want to prohibit developers interacting with the database or Nakama subsystems in these event hooks. This encourages bad design and could actually end up being a DDoS vector when many users connect/disconnect from the system (say in a bad networking scenario - stampeding herd problem: https://en.wikipedia.org/wiki/Thundering_herd_problem)

Makes sense. Thanks!

Any plans to add this server function in lua? Thx!

@amesa We don’t plan to expose this particular API to the Lua runtime because its called very heavily when sockets connect and disconnect as well as when custom events are executed in various server features or any of your custom server logic. We do have support for creating events in Lua so they can be captured into the event processor.

I think this is the only API and will likely remain the only one that has specific execution characteristics that require Go code.

In our previous game using other backend (Gamesparks), we were doing actions when the player disconnected, like enabling a shield with a timer for their city to avoid being attacked.
How do you recommend to do this in Nakama?

The problem with mobile devices it is that the user can exit the application in differents ways, when an user goes to background we are not closing the socket, because the user may have the app in background only for a short period of time, this happens during purchases, watching a video-ad or just when checking another mobile app.

Thanks you!

@amesa I think you’ll need to share more detail on the game design for this shield feature. From what it sounds like you’ll protect the player while they’re otherwise engaged on the mobile device. Isn’t this open to abuse where a player would background the app to prevent being attacked for some time? I’ve never heard of or seen a game with this kind of feature.

Hi again! Sorry to answer late.
What we did is to save in the player metadata a date when the player disconnected. Then we used that “last connection date” to do things.
I just wanted to use it as an example of doing something when the player disconnects.

1 Like