Send push messages
Push messages to clients over a WebSocket connection from Cloud Code modules.
Read time 13 minutesLast updated 16 hours ago
Cloud Code C# modules allow you to push messages to clients over a WebSocket. This page provides an overview of this feature and instructions on how to use it in Cloud Code modules and the Cloud Code SDK.
To send push messages, you need to call a module endpoint. You can subscribe to push messages from the Unity Editor.
Use cases and benefits
You can use push messages for a variety of purposes, such as the following:
Use | Example | Benefit |
|---|---|---|
| Push messages from the server to clients in real time and enhance interactivity for your games. | You can notify players about game events, updates, or asynchronous multiplayer games (for example, competitive card games). Refer to Turn change notification patterns for how synchronous and asynchronous Stateful Cloud Code games use push messages differently. | Real-time interaction |
| Keep users up-to-date with the latest events, changes, or actions in the game by pushing updates and notifications directly to the client. | You can notify your users as soon as new data is available so you don't need to manually refresh or check for updates. This can be especially useful for games that require frequent updates, such as real-time strategy games. | User experience |
| Use WebSockets to push messages for more efficiency than traditional polling techniques. | Your client can wait for the server to send new data when it becomes available instead of continuously asking the server for new data. This reduces unnecessary network traffic and can lead to lower latency. | Efficient network usage |
| Use the scalability of the push model to support games with a large number of users. | You can use push messages in Cloud Code to send updates to all connected clients at once, and reduce the operating cost and amount of requests for multiplayer games with a large number of players. | Scalability and cost |
| Customize your game's response to different types of messages with the event-driven model. | You can trigger different game actions based on the | Customizability |
| As part of the Unity ecosystem, use Cloud Code is seamlessly with other Unity services. | You can handle player authentication with Unity's Authentication service, and process the messages within the Unity game engine. | Seamless integration |
Create a module
The following code example demonstrates the basic structure for a module that includes two methods:
- : sends a message to a specific connected player.
SendPlayerMessage - : broadcasts a message to all connected players in the project.
SendProjectMessage
Cloud Code provides the interface, which you use to send push messages. exposes methods that publish a message to a WebSocket connection, either to one player or to every player subscribed in the project. Only clients that are already subscribed receive the message. Inject as a parameter in a method, as the following example demonstrates:
IPushClientIPushClientIPushClientCloudCodeFunctionusing System.Threading.Tasks;using Unity.Services.CloudCode.Core;namespace PushExample{ public class PushExample { [CloudCodeFunction("SendPlayerMessage")] public async Task<string> SendPlayerMessage(IExecutionContext context, IPushClient pushClient, string message, string messageType, string playerId) { // Send the message to a single player. var response = await pushClient.SendPlayerMessageAsync(context, message, messageType, playerId); return "Player message sent"; } // Recommended to use access control to limit access to this endpoint [CloudCodeFunction("SendProjectMessage")] public async Task<string> SendProjectMessage(IExecutionContext context, IPushClient pushClient, string message, string messageType) { // Broadcast the message to every subscribed player in the project. var response = await pushClient.SendProjectMessageAsync(context, message, messageType); return "Project message sent"; } }}
To learn how to deploy a module, refer to the Deploying Hello World page.
Set up the Unity Editor
The Cloud Code SDK provides an interface for subscribing to messages. You can subscribe to messages for a specific player or for the entire project.
To use Cloud Code in the Unity Editor, you must first install the Cloud Code SDK and link your Unity Gaming Services project to the Unity Editor.
Link project
Link your Unity Gaming Services project with the Unity Editor. You can find your UGS project ID in the Unity Dashboard.
-
In Unity Editor, select Edit > Project Settings > Services.
-
Link your project.
If your project doesn't have a Unity project ID:- Select Create a Unity Project ID > Organizations, then select an organization from the dropdown.
- Select Create project ID.
If you have an existing Unity project ID:- Select Use an existing Unity project ID.
- Select an organization and a project from the dropdowns.
- Select Link project ID.
This shows your Unity Project ID and links the project to Unity services. You can also access your project ID in a Unity Editor script with the parameter.
UnityEditor.CloudProjectSettings.projectIdSDK installation
Install the latest Cloud Code package for Unity Editor:
- In the Unity Editor, open Window > Package Manager.
- In the Package Manager, select the Unity Registry list view.
- Search for , or locate the Cloud Code package in the list.
com.unity.services.cloudcode - Select the package, then click Install.
SDK setup
Get started with the Cloud Code SDK:
- Ensure the service is enabled via the Cloud Code service dashboard page.
- Ensure that you have installed both the Cloud Code and the Authentication SDKs.
- Sign into your cloud project from within Unity Editor by selecting Edit > Project Settings > Services.
- Create a new C# Monobehaviour script in Unity Editor. Refer to Creating and using scripts in the Unity Manual.
- In the script, initialize the Core SDK using await .
UnityServices.InitializeAsync() - In the script, initialize the Authentication SDK.
await AuthenticationService.Instance.SignInAnonymouslyAsync();
Subscribe to messages
You can subscribe to messages for a specific player or for the entire project. You can use the following code snippet as a guide for a script for your Unity project.
MonoBehaviourThe script authenticates as an anonymous player, and subscribes to both player-specific and project-specific messages and handles various types of events:
using System;using System.Threading.Tasks;using Newtonsoft.Json;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.CloudCode.Subscriptions;using Unity.Services.Core;using UnityEngine;namespace CloudCode{ public class CloudCodePushExample : MonoBehaviour { async void Start() { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log(AuthenticationService.Instance.PlayerId); await SubscribeToPlayerMessages(); await SubscribeToProjectMessages(); } // This method creates a subscription to player messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToPlayerMessages() { // Register callbacks, which are triggered when a player message is received var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got player subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got player subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got player subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got player subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToPlayerMessagesAsync(callbacks); } // This method creates a subscription to project messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToProjectMessages() { var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got project subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got project subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got project subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got project subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToProjectMessagesAsync(callbacks); } }}
Send messages to players
To send messages to players, call either the or the function from your module.
SendPlayerMessageSendProjectMessageTo learn how to run modules, refer to Run modules.
Run from Unity runtime
You can send messages to other players via the method of the instance. You need to use the module name and function name as its first two arguments, and a dictionary with the necessary parameters as the third argument.
CallModuleEndpointAsyncCloudCodeServiceFor example, to send a player message, you can call:
var sendPlayerMessageResult = await CloudCodeService.Instance.CallModuleEndpointAsync<string>("PushExample", "SendPlayerMessage", new Dictionary<string, object> {{"message", "hello with a player message from PushExample!"}, {"messageType", "testType"}, {"playerId", "<other-unity-player-ID>"}});
Send messages to a scope
To send one message to every player in a scope, such as all the players in a multiplayer session, use scope messages. For more information about scopes, refer to State scopes. A scope message reaches the players who subscribed to that scope, instead of one player or the whole project.
Scope messages work only in a scoped module function. Cloud Code sends the message to the scope that the current call runs in, so a function can't send messages to another scope.
Send scope messages from a module
Add a function that returns a subscription token, and a function that sends the message. The following -scoped module also removes a player who leaves the session:
MultiplayerSessionusing System.Threading.Tasks;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCodePush.Model;namespace PushExample{ [StateScope(Scope.MultiplayerSession)] public class MatchMessages { // Returns a token that lets the calling player subscribe to this scope. [CloudCodeFunction("GetScopeToken")] public Task<GenerateTokenReply> GetScopeToken(IExecutionContext context, IPushClient pushClient) { return pushClient.GenerateScopeTokenAsync(context); } // Sends one message to every player subscribed to this scope. [CloudCodeFunction("SendMatchMessage")] public async Task SendMatchMessage(IExecutionContext context, IPushClient pushClient, string message, string messageType) { await pushClient.SendScopeMessageAsync(context, message, messageType); } // Stops a player who left the session from receiving this scope's messages. // Only the session host and service accounts can call this function. [CloudCodeFunction("RemovePlayer", Access.SessionHost)] public async Task RemovePlayer(IExecutionContext context, IPushClient pushClient, string playerId) { await pushClient.ForceUnsubscribeFromScopeMessagesAsync(context, playerId); } }}
A message can be up to 10 KB, and its property up to 128 characters.
MessageTypeOnly a player who can call the token function can subscribe, so the function's access rules control who receives the scope's messages. By default, every member of a scope can call the token function. For more information, refer to Function access control.
MultiplayerSessionA token is valid for 1 hour. When it expires, the Cloud Code SDK calls the token function again to get a new one. On the local Cloud Code server, tokens don't expire.
Subscribe to scope messages
In your game, call with the module name, the name of the token function, and the scope. The following example subscribes to the messages of a session that the player joined with Multiplayer Services, and logs each message it receives:
SubscribeToScopeMessagesAsyncusing System.Threading.Tasks;using Unity.Services.CloudCode;using Unity.Services.CloudCode.Subscriptions;using UnityEngine;public class MatchMessagesClient : MonoBehaviour{ // sessionId is the ID of a session that the player joined. public async Task SubscribeToMatchMessages(string sessionId) { var scope = new CloudCodeScope(ScopeType.MultiplayerSession, sessionId); var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log($"Got scope message of type {@event.MessageType}: {@event.Message}"); }; await CloudCodeService.Instance.SubscribeToScopeMessagesAsync("PushExample", "GetScopeToken", scope, callbacks); }}
If the token function fails, for example because the player doesn't have access, throws the from that call.
SubscribeToScopeMessagesAsyncCloudCodeExceptionEvents
Player, project, and scope subscriptions have four event handlers:
- : triggers when the player receives a new message.
MessageReceived - : triggers when the state of the connection changes.
ConnectionStateChanged - : triggers when the server forcefully unsubscribes the player from messages. This doesn't close the WebSocket connection, nor does it prevent the game client from subscribing to messages again.
Kicked - : triggers when an error occurs in handling the connection or when the player receives messages.
Error
Message envelope
The is an interface that represents a message the player receives from the push service. The event triggers when Cloud Code sends a message via a WebSocket connection.
IMessageReceivedEventRefer to the table below for the payload of the interface:
IMessageReceivedEventProperty | Description | Example |
|---|---|---|
| The specification version of the received message's envelope. Use this property to ensure the client can process the message correctly. | 1.0 |
| A unique identifier for the message. Use this property to track or log messages. | |
| The source of the message's envelope. This indicates where the message originated from, which you can use to debug or route messages. The source is always the domain of Cloud Code. | |
| The message's envelope type. This property indicates the type of data the message contains and helps the client decide how to process it. The value is always a Cloud Code message type. | |
| The date and time of the message creation. You can use this property to log the messages, or to calculate latency. | |
| The ID of the project the message is associated with. | |
| The ID of the environment that the message is for. You can use this property to differentiate between different environments such as development, staging, and production. | |
| An identifier that you can use to track a sequence of related messages. For instance, if multiple messages form a conversation or workflow, they might share a correlation ID. | |
| The actual message content sent from Cloud Code to the player. | "hello world!" |
| The type of the message that the player receives. This is similar to | "Information" |