Publish/Subscribe API for PubNub Unity SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
publish()
sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Message serialization
- Custom message type
- Best practices
- You must initialize PubNub with the
publishKey
. - You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
You can secure the messages with SSL/TLS by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. String content can include any single-byte or multi-byte UTF-8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large
error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
You can publish as fast as bandwidth conditions allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Sending structures with circular references (like Vector3) may cause issues depending on your JSON library settings. In those cases, you can use the GetJsonSafe()
extension method included in the PubNub namespace.
pubnub.Publish().Channel(defaultChannel).Message(transform.GetJsonSafe()).Execute((a, b) => { });
pubnub.Publish().Channel(defaultChannel).Message(transform.position.GetJsonSafe()).Execute((a, b) => { });
pubnub.Publish().Channel(defaultChannel).Message(transform.localRotation.GetJsonSafe()).Execute((a, b) => { });
You can optionally provide the CustomMessageType
parameter to add your business-specific label or category to the message, for example text
, action
, or poll
.
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts according to your app's latency needs, for example no more than 5 messages per second.
Method(s)
To Publish a message
you can use the following method(s) in the Unity SDK:
pubnub.Publish()
.Message(object)
.Channel(string)
.ShouldStore(bool)
.Meta(Dictionary<string, object>)
.UsePOST(bool)
.Ttl(int)
.QueryParam(Dictionary<string,object>)
.CustomMessageType(string)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the Message . |
ShouldStore | bool | Optional | Store in history. If ShouldStore is not specified, then the history configuration on the key is used. |
Meta | Dictionary<string, object> | Optional | Meta data object which can be used with the filtering ability. |
UsePOST | bool | Optional | Use POST to Publish . |
Ttl | int | Optional | Set a per message time to live in storage.
|
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
CustomMessageType | string | Optional | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . |
Sync | Command | Optional | Block the thread, exception thrown if something goes wrong. |
Async | PNCallback | PNCallback of type PNPublishResult . | |
Execute | System.Action | Optional | System.Action of type PNPublishResult . |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Publish a message to a channel
//Publishing Dictionary
Dictionary<string, float> position = new Dictionary<string, float>();
position.Add("lat", 32F);
position.Add("lng", 32F);
Debug.Log("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position));
PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
.Message(position)
.Channel("my_channel")
.CustomMessageType("text-message")
.ExecuteAsync();
PNPublishResult publishResult = publishResponse.Result;
PNStatus status = publishResponse.Status;
Debug.Log("pub timetoken: " + publishResult.Timetoken.ToString());
show all 16 linesSubscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Returns
The Publish()
operation returns a PNResult<PNPublishResult>
which contains the following properties:
Property Name | Type | Description |
---|---|---|
Result | PNPublishResult | Returns a PNPublishResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNPublishResult
contains the following properties:
Property Name | Type | Description |
---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was published. |
Other Examples
Publish a message to a channel synchronously
//Publishing Dictionary
Dictionary<string, float> position = new Dictionary<string, float>();
position.Add("lat", 32F);
position.Add("lng", 32F);
Debug.Log("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position));
pubnub.Publish()
.Message(position)
.Channel("my_channel")
.CustomMessageType("text-message")
.Execute(new PNPublishResultExt(
(result, status) => {
Debug.Log("pub timetoken: " + result.Timetoken.ToString());
Debug.Log("pub status code : " + status.StatusCode.ToString());
show all 17 linesPublish with metadata
string[] arrayMessage = new string[] {
"hello",
"there"
};
pubnub.Publish()
.Message(arrayMessage.ToList())
.Channel("suchChannel")
.ShouldStore(true)
.Meta("<json data as dictionary object>")
.UsePOST(true)
.CustomMessageType("text-message")
.Execute((result, status) => {
// handle publish result, status always present, result if successful
// status.Error to see if error happened
show all 17 linesStore the published message for 10 hours
PNPublishResult res = pubnub.Publish()
.Channel("coolChannel")
.Message("test")
.ShouldStore(true)
.Ttl(10)
.CustomMessageType("text-message")
.Sync();
Publishing messages for receipt on FCM and APNS associated devices, sample payload
public class MobilePayload
{
public Dictionary<string, object> pn_apns;
public Dictionary<string, object> pn_gcm;
public Dictionary<string, object> full_game;
}
Dictionary<string, object> apnsData = new Dictionary<string, object>();
apnsData.Add("aps", new Dictionary<string, object>() {
{ "alert", "Game update 49ers touchdown" },
{ "badge", 2 }
});
apnsData.Add("teams", new string[] { "49ers", "raiders" });
apnsData.Add("score", new int[] { 7, 0 });
show all 54 linesFor more details, refer to Mobile Push.
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Unity SDK:
pubnub.Fire()
.Message(object)
.Channel(string)
.Meta(Dictionary<string, object>)
.UsePOST(bool)
.QueryParam(Dictionary<string,object>)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the message . |
Meta | Dictionary<string, object> | Optional | Meta data object which can be used with the filtering ability. |
UsePOST | bool | Optional | Use POST to Publish . |
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Sync | Command | Optional | Block the thread, exception thrown if something goes wrong. |
Async | PNCallback | PNCallback of type PNPublishResult | |
Execute | System.Action | Optional | System.Action of type PNPublishResult |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Fire a message to a channel
string[] arrMessage = new string[] {
"hello",
"there"
};
pubnub.Fire()
.Message(arrMessage.ToList())
.Channel(channel)
.UsePOST(true)
.Execute((result, status) => {
if (status.Error) {
// something bad happened.
Debug.Log("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
} else {
Debug.Log("publish worked! timetoken: " + result.Timetoken.ToString());
show all 18 linesSignal
The signal()
function is used to send a signal to all subscribers of a channel.
By default, signals are limited to a message payload size of 64
bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.
Method(s)
To Signal a message
you can use the following method(s) in the Unity SDK:
pubnub.Signal()
.Message(object)
.Channel(string)
.CustomMessageType(string)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the Message . |
CustomMessageType | string | Optional | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . |
Execute | System.Action | Optional | System.Action of type PNPublishResult . |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Signal a message to a channel
Dictionary<string, string> myMessage = new Dictionary<string, string>();
myMessage.Add("msg", "Hello Signals");
pubnub.Signal()
.Message(myMessage)
.Channel("foo")
.CustomMessageType("text-message")
.Execute((result, status) => {
if (status.Error) {
Debug.Log(status.ErrorData.Information);
} else {
Debug.Log(result.Timetoken);
}
});
Response
Property Name | Type | Description |
---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was signaled. |
Subscribe
The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey
at initialization.
Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:
A newly subscribed client receives messages after the subscribe()
call completes. You can configure automaticRetry
to attempt to reconnect automatically and retrieve any available messages if a client gets disconnected.
Subscription scope
Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:
Subscription
, created from an entity with a scope of only that entity (for example, a particular channel)SubscriptionSet
, created from the PubNub client with a global scope (for example, all subscriptions created on a singlepubnub
object ). A subscription set can have one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Create a subscription
An entity-level Subscription
allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscription
s is useful for handling various message/event types differently in each channel.
Keep a strong reference
You should keep a strong reference to every created subscription/subscription set because they must stay in memory to listen for updates. If you were to create a Subscription
/SubscriptionSet
and not keep a strong reference to it, Automatic Reference Counting (ARC) could deallocate the Subscription
as soon as your code finishes executing.
// entity-based, local-scoped
Channel firstChannel = pubnub.Channel("first");
Subscription subscription = firstChannel.Subscription(SubscriptionOptions options);
Parameter | Type | Required | Description |
---|---|---|---|
options | SubscriptionOptions | No | Subscription behavior configuration. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
Keep a strong reference
You should keep a strong reference to every created subscription/subscription set because they must stay in memory to listen for updates. If you were to create a Subscription
/SubscriptionSet
and not keep a strong reference to it, Automatic Reference Counting (ARC) could deallocate the Subscription
as soon as your code finishes executing.
// client-based, general-scoped
SubscriptionSet subscriptionSet = pubnub.SubscriptionSet(
channels: string[],
channelGroups: string[],
options: SubscriptionOptions
)
Parameter | Type | Required | Description |
---|---|---|---|
channels | string[] | Yes | One or more channels to create a subscription of. Either channels or channelGroups is required. |
channelGroups | string[] | Yes | One or more channels to create a subscription of. Either channels or channelGroups is required. |
options | SubscriptionOptions | No | Subscription behavior configuration. |
Add/remove sets
You can add and remove subscriptions to create new sets. Refer to the Other examples section for more information.
SubscriptionOptions
SubscriptionOptions
is an enum. Available properties include:
Option | Description |
---|---|
ReceivePresenceEvents | Whether presence updates for userId should be delivered through the listener streams. |
Method(s)
Subscription
and SubscriptionSet
use the same subscribe<object>()
method.
Subscribe
To subscribe, you can use the following method in the Swift SDK:
subscription.Subscribe<object>(SubscriptionCursor cursor)
Parameter | Type | Required | Description |
---|---|---|---|
cursor | SubscriptionCursor | No | Cursor from which to return any available cached messages. Message retrieval with cursor is not guaranteed and should only be considered a best-effort service. A cursor consists of a timetoken and region: cursor: { Timetoken: long?; Region: int? } If you pass any primitive type, the SDK converts them into SubscriptionCursor but if their value is not a 17-digit number or a string with numeric characters, the provided value will be ignored. |
Basic usage
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
subscription1.Subscribe<object>()
SubscriptionSet subscriptionSet = pubnub.Subscription(
new string[] {"channel1", "channel2"},
new string[] {"channel_group_1", "channel_group_2"},
SubscriptionOptions.ReceivePresenceEvents
)
subscriptionSet.Subscribe<object>()
Other examples
Create a subscription set from 2 individual subscriptions
// Create a subscription from a channel entity
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
// Create a subscription from a channel group entity
Subscription subscription2 = pubnub.ChannelGroup("channelGroupName").Subscription()
// create a subscription set from individual entities
SubscriptionSet subscriptionSet = subscription1.Add(subscription2)
subscriptionSet.Subscribe<object>()
Returns
The subscribe()
method doesn't have a return value.
Entities
Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).
ChannelRepresentation
ChannelGroupRepresentation
UserMetadataRepresentation
ChannelMetadataRepresentation
Create channels
This method returns a local Channel
entity.
pubnub.Channel(String)
Parameter | Type | Required | Description |
---|---|---|---|
Channel | String | Yes | The name of the channel to create a subscription of. |
Basic usage
pubnub.Channel("channelName")
Create channel groups
This method returns a local ChannelGroup
entity.
pubnub.ChannelGroup(String)
Parameter | Type | Required | Description |
---|---|---|---|
ChannelGroup | String | Yes | The name of the channel group to create a subscription of. |
Basic usage
pubnub.ChannelGroup("channelGroupName")
Create channel metadata
This method returns a local ChannelMetadata
entity.
pubnub.ChannelMetadata(String)
Parameter | Type | Required | Description |
---|---|---|---|
ChannelMetadata | String | Yes | The String identifier of the channel metadata object to create a subscription of. |
Basic usage
pubnub.ChannelMetadata("channelMetadata")
Create user metadata
This method returns a local UserMetadata
entity.
pubnub.UserMetadata(String)
Parameter | Type | Required | Description |
---|---|---|---|
UserMetadata | String | Yes | The String identifier of the user metadata object to create a subscription of. |
Basic usage
pubnub.UserMetadata("userMetadata")
Event listeners
Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.
You can attach listeners to the instances of Subscription
, SubscriptionSet
, and, in the case of the connection status, the PubNub client.
Add listeners
You can implement multiple listeners with the onEvent
closure or register an event-specific listener that receives only a selected type, like message
or file
.
Method(s)
// Add event-specific listeners
// Add a listener to receive Message changes
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
subscription1.OnMessage = (Pubnub pn, PNMessageResult<object> messageEvent) => {
Console.WriteLine($"Message received {messageEvent.Message}");
};
subscription1.Subscribe<object>()
// Add multiple listeners
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
delegate (Pubnub pn, PNMessageResult<object> messageEvent) {
Console.WriteLine($"received message {messageEvent.Message}");
show all 37 linesBasic usage
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
SubscriptionSet subscriptionSet = pubnub.Subscription(
new string[] {"channel1", "channel2"},
new string[] {"channel_group_1", "channel_group_2"},
SubscriptionOptions.ReceivePresenceEvents
)
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
delegate (Pubnub pn, PNMessageResult<object> messageEvent) {
Console.WriteLine($"received message {messageEvent.Message}");
}
)
show all 22 linesAdd connection status listener
The PubNub client has a listener dedicated to handling connection status updates.
Client scope
This listener is only available on the PubNub object.
Method(s)
pubnub.AddListener(listener)
Basic usage
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
delegate (Pubnub pn, PNStatus e) {
Console.WriteLine("Status event");
}
);
pubnub.AddListener(eventListener)
Returns
The subscription status. For information about available statuses, refer to SDK statuses.
Unsubscribe
Stop receiving real-time updates from a Subscription
or a SubscriptionSet
.
Method(s)
subscription.Unsubscribe<object>()
subscriptionSet.Unsubscribe<object>()