User Online/Offline Hooks
Introduction
The framework provides hook interfaces for user online/offline events. Developers can use them for special business logic. Used properly, these hooks can notify logic servers of current user online state:
- For example, when user goes offline, send an action to logic server to process offline business logic.
- For example, in a chess table with two players, if user A disconnects, you can notify user B and mark player A avatar as offline.
UserHook is the hook interface for online/offline events and provides two methods:
- into: triggered after user login succeeds.
- quit: triggered after connection is disconnected.
Framework includes default implementation DefaultUserHook, which only logs simple messages.
This section explains how to extend UserHook.
warning
Hook interface is triggered only after login.
Example Source Code
see https://github.com/iohao/ionet-examples
path : ionet-cookbook-code
- MyUserHook
- MyExternalServer
Custom UserHook
Now we define a custom MyUserHook implementing 2 interfaces:
UserHook: hooks for user online/offline.ExternalSettingAware: after implementing it, framework injectsExternalSetting. From that object we can obtainUserSessionsandConvenientCommunication.
Code description
- code 7: print current connected userId and count current online users in external server.
- code 15~16: when user goes offline, send an action request to logic server for subsequent offline processing.
- code 21~22: set
UserSessionsandConvenientCommunicationused for communication.
public final class MyUserHook implements UserHook, ExternalSettingAware {
UserSessions<?, ?> userSessions;
ConvenientCommunication convenientCommunication;
@Override
public void into(UserSession userSession) {
log.info(getString(userSession, "online"));
}
@Override
public void quit(UserSession userSession) {
log.info(getString(userSession, "offline"));
// Send an offline message
var message = userSession.ofMessage(HallCmd.of(HallCmd.internalOffline));
this.convenientCommunication.request(message);
}
@Override
public void setExternalSetting(ExternalSetting setting) {
this.userSessions = setting.userSessions();
this.convenientCommunication = setting.convenientCommunication();
}
private String getString(UserSession userSession, String key) {
return """
%s:%s
userId:%s
userChannelId:%s
""".formatted(
key, this.userSessions.countOnline(),
userSession.getUserId(),
userSession.getUserChannelId());
}
}
Setting UserHook
Set custom MyUserHook to external server.
public ExternalServerBuilder builder(int port, ExternalJoinEnum joinEnum) {
var builder = ExternalMapper.builder(port, joinEnum);
builder.setUserHook(new MyUserHook());
return builder;
}