Skip to content

Callbacks

uwee edited this page Feb 10, 2019 · 3 revisions

When sending a message you may sometimes need to wait for that reply to continue the game logic. Below is an example usage of callbacks from the Login Example.

public void SendLoginMsg(string username, string password)
{
    client.Send((short)MsgId.Login, new LoginMsg() { 
        AccountName = username, 
        AccountPassword = Sha256(password) }, (callbackStatus, reader) =>
        {
            if (callbackStatus == CallbackStatus.Ok)
            {
                StatusMsg msg = reader.ReadMessage<StatusMsg>();
                loginResponse = msg.Text;
                loginSucessful = true; //This will always be true for prototyping
                Debug.Log(msg.Text);
            }
            if (callbackStatus == CallbackStatus.Error)
            {
                Debug.LogError("Callback Error: Login error");
            }
            if (callbackStatus == CallbackStatus.Timeout)
            {
                Debug.LogError("Callback Error: Login attempt timed out");
            }
    });
}

Then on the server side the message is handled and a .Reply is used to include the CallbackID for proper handling back on the client side.

private void HandleLoginMsg(InsightNetworkMessage netMsg)
{
    LoginMsg message = netMsg.ReadMessage<LoginMsg>();
        
    if (server.logNetworkMessages) { Debug.Log("[InsightServer] - Login Received: " + message.AccountName + " / " + message.AccountPassword); }

    registeredUsers.Add(new UserContainer() { 
        username = message.AccountName, 
        uniqueId = Guid.NewGuid().ToString(), 
        connectionId = netMsg.connectionId});

    netMsg.Reply((short)MsgId.Status, new StatusMsg() { Text = "Login Sucessful!" });
}

Callbacks can also be initiated from a Server to a Client. In other instances you may need to chain multiple callbacks together. This is done in the GameManager example.

Clone this wiki locally