TGB/Networking/Messages
From TDN
TGB Networking >> Sending Messages From Server to Clients
Sending Messages From Server to Clients
message.cs in common/gameScripts/server contains five useful methods for a server to send messages to connected clients. Unlike remote procedure calls which are the primary means for communication between server and client, messages are a simpler and lightweight way of passing a "message" from the server to one or more clients. These messages are different from a standard remote procedure call in that a message is simply defined by a message "type" string and the message content itself.
The methods available to send messages are:
- messageClient(%client, %messageType, %message)
- messageAll(% messageType, %message)
- messageAllExcept(%client, %team, % messageType, %message)
- messageTeam(%team, % messageType, %message)
- messageTeamExcept(%client, % messageType, %message)
Teams are determined by the client's team field value in the connection object within ClientGroup. As of TGB 1.7.2, however, there is no method that sets the team value for players. That logical will likely vary from game to game, so if you need support for sending messages to a specific team only, you will need to add the appropriate logic to assign players to teams on the server.
To receive a message, you need to add a message handler by calling the addMessageCallback() function, passing the message "type", and the name of a function which will handle that message. For example, when a client connects to the server, the server then sends a message using messageAllExcept() to notify all other clients that a new client has connected. By default, this "ClientJoined" message is handled by the clientJoined() function which was added as the message handler using:
addMessageCallback('ClientJoined', clientJoined);
The message content passed to the messageAllExcept() method on the server, is the first and only parameter to all message handler callbacks. The message handler callback for the "ClientJoined" message looks like:
function clientJoined(%client)
{
echo("ClientJoined: " @ %client.name);
}
Messages sent by the server which do not have a message handler in the client, are sent to the defaultMessageCallback() function which simply calls the onServerMessage(%message) callback.
Categories: Networking | Server | Client | TGB



