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

Description

The Publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid PublishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data should not contain special Unity V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

Don't JSON serialize!

It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error

["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-Message-Payload-Size-Before-Publish

Message Publish Rate

Messages can be published as fast as bandwidth conditions will 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 messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (e.g. [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 in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.

Method(s)

To Publish a message you can use the following method(s) in the Unity V4 SDK:

pubnub.Publish().Channel(string).Message(object).UsePost(bool).ShouldStore(bool).Meta(Dictionary<string,string>).PublishAsIs(bool).Ttl(int).QueryParam(Dictionary<string,string>).Async()
ParameterTypeRequiredDefaultDescription
ChannelstringYesDestination of the message.
MessageobjectYesThe payload.
UsePOSTboolOptionalfalseUse POST to publish.
ShouldStoreboolOptionalaccount defaultStore in history.
If shouldStore is not specified, then the history configuration on the key is used.
MetaDictionary<string,string>OptionalNot setMeta data object which can be used with the filtering ability.
PublishAsIsboolOptionalfalseIt should be set to true when you are going to Publish a JSON serialized string.
By default it is set to false and the SDK takes care of JSON serializing the message for you.
TtlintOptionalSet a per message time to live in storage.
  1. If shouldStore = true, and Ttl = 0, the message is stored with no expiry time.
  2. If shouldStore = true and Ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
  3. If shouldStore = false, the Ttl parameter is ignored.
  4. If Ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
AsyncPNCallbackOptionalPNCallback of type PNPublishResult

Basic Usage

Publish a message to a channel

pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
Subscribe 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 PNPublishResult which contains the following operations:

MethodTypeDescription
TimetokenlongReturns a long representation of the timetoken when the message was published.

Other Examples

Publish with metadata

Dictionary<string, string> metaDict = new Dictionary<string, string>();
metaDict.Add("region", "east");

pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Meta(metaDict)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});

Store the published message for 10 hours

pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Ttl(10)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});

Push Payload Helper

You can use the helper method as an input to the Message parameter, to format the payload for publishing Push messages. For more info on the helper method, check Create Push Payload Helper Section

CreatePushPayloadHelper cpph = new CreatePushPayloadHelper();
PNAPSData aps = new PNAPSData();
aps.Alert = "alert";
aps.Badge = 1;
aps.Sound = "ding";
aps.Custom = new Dictionary<string, object>(){
{"aps_key1", "aps_value1"},
{"aps_key2", "aps_value2"},
};

PNAPNSData apns = new PNAPNSData();
apns.APS = aps;
apns.Custom = new Dictionary<string, object>(){
{"apns_key1", "apns_value1"},
{"apns_key2", "apns_value2"},
show all 84 lines

Fire

Description

The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. 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 V4 SDK:

pubnub.Fire().Channel(string).Message(object).Meta(Dictionary<string,string>).PublishAsIs(bool).usePOST(bool).Ttl(int).QueryParam(Dictionary<string,string>).Async()
ParameterTypeRequiredDefaultDescription
ChannelstringYesDestination of the message.
MessageobjectYesThe payload.
MetaDictionary<string,string>OptionalNot setMeta data object which can be used with the filtering ability.
PublishAsIsboolOptionalfalseIt should be set to true when you are going to Publish a JSON.
usePOSTboolOptionalfalseUse POST to publish.
TtlintOptionalSet a per message time to live in storage.
  1. If shouldStore = true, and ttl = 0, the message is stored with no expiry time.
  2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
  3. If shouldStore = false, the ttlparameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
AsyncPNCallbackOptionalPNCallback of type PNPublishResult

Basic Usage

Fire a message to a channel

pubnub.Fire()
.Channel("my_channel")
.Message("test fire message")
.Async((result, status) => {
if(status.Error){
Debug.Log (status.Error);
Debug.Log (status.ErrorData.Info);
} else {
Debug.Log (string.Format("Fire Timetoken: {0}", result.Timetoken));
}
});

Signal

Description

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 V4 SDK:

pubnub.Signal().Message(object).Channel(string).Async()
ParameterTypeRequiredDescription
MessageobjectYesThe payload.
ChannelstringYesDestination of the Message.
AsyncPNCallbackOptionalPNCallback of type PNSignalResult

Basic Usage

Signal a message to a channel

pubnub.Signal()
.Channel("my_channel")
.Message("test signal message")
.Async((result, status) => {
if(status.Error){
Debug.Log (status.Error);
Debug.Log (status.ErrorData.Info);
} else {
Debug.Log (string.Format("Signal Timetoken: {0}", result.Timetoken));
}
});

Response

Property NameTypeDescription
TimetokenlongReturns a long representation of the timetoken when the message was signaled.

Subscribe

Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate SubscribeKey at initialization.

By default a newly subscribed client will only receive messages published to the channel after the Subscribe() call completes. If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting ReconnectionPolicy to PNReconnectionPolicy.LINEAR, when initializing the client.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Subscribe to a channel you can use the following method(s) in the Unity V4 SDK:

pubnub.Subscribe().Channels(List<string>).ChannelGroups(List<string>).SetTimeToken(long).WithPresence(bool).QueryParam(Dictionary<string,string>).Execute(Command);
ParameterTypeRequiredDescription
ChannelsList<string>OptionalSubscribe to channels, Either channel or channelGroup is required.
ChannelGroupsList<string>OptionalSubscribe to channel groups, Either channel or channelGroup is required.
SetTimetokenlongOptionalPass a timetoken.
WithPresenceboolOptionalAlso subscribe to related presence information.
QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
Execute()CommandYesCommand that will execute subscribe.

Basic Usage

Subscribe to a channel:

pubnub.Subscribe()
.Channels(new List<string>() {
"my_channel"
})
.Execute();
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Returns

Event listeners

PNMessageResult is returned in the Listeners

The Subscribe() operation returns a PNStatus which contains the following operations:

Property NameTypeDescription
CategoryPNStatusCategoryDetails of PNStatusCategory are here
ErrorboolThis is true if an error occurred in the execution of the operation.
ErrorDataPNErrorDataError data of the exception (if Error is true)
StatusCodeintStatus code of the excution.
OperationPNOperationTypeOperation type of the request.
AffectedChannelsList<string>A list of affected channels in the operation.
AffectedChannelGroupsList<string>A list of affected channel groups in the operation.

The Subscribe() operation returns a PNMessageResult, for both Publish and Signal messages, which contains the following operations:

MethodTypeDescription
PayloadobjectThe message sent on the channel.
SubscriptionstringThe channel group or wildcard subscription match (if exists).
ChannelstringThe channel for which the message belongs.
TimetokenlongTimetoken for the message.
UserMetadataobjectUser metadata.

The Subscribe() operation returns a PNPresenceEventResult from presence which contains the following operations:

MethodTypeDescription
EventstringEvents like join, leave, timeout, state-change, interval.
UUIDstringUUID for the event.
TimestamplongTimestamp for the event.
OccupancyintCurrent occupancy.
StateobjectState of the UUID.
SubscriptionstringThe channel group or wildcard subscription match (if exists).
ChannelstringThe channel for which the message belongs.
TimetokenlongTimetoken of the message.
UserMetadataobjectUser metadata.

Other Examples

Basic subscribe with logging

PNConfiguration pnConfiguration = new PNConfiguration ();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
pubnub = new PubNub (pnConfiguration);
pubnub.Subscribe ().Channels(new List<string> (){"my_channel"}).Execute();

Subscribing to multiple channels

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

pubnub.Subscribe().
Channels(new List<string> (){"my_channel", "my_channel2"})
.Execute();
Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres. Presence data can be observed inside the SubscribeCallback#message(PubNub, PNMessageResult) callback.

pubnub.Subscribe()
.Channels(new List<string>() {
"my_channel"
})
.WithPresence()
.Execute();

Sample Responses

Join Event

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if(mea.PresenceEventResult.Event.Equals("join")){
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy);
}
};

Leave Event

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if(mea.PresenceEventResult.Event.Equals("leave")){
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy);
}
};

Timeout Event

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if(mea.PresenceEventResult.Event.Equals("timeout")){
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy);
}
};

Custom Presence Event (State Change)

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if(mea.PresenceEventResult.Event.Equals("state-change")){
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy);
}
};

Interval Event

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if(mea.PresenceEventResult.Event.Equals("interval")){
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy);
}
};

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if (mea.PresenceEventResult.Event.Equals("interval")) {
Debug.Log(mea.PresenceEventResult.UUID);
Debug.Log(mea.PresenceEventResult.Timestamp);
Debug.Log(mea.PresenceEventResult.Occupancy) ;
Debug.Log(string.Join(",",mea.PresenceEventResult.Join.ToArray()));
Debug.Log(string.Join(",",mea.PresenceEventResult.Timeout.ToArray()));
}
};

If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

{
"Event": "interval",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": <unix timestamp>,
"Occupancy": <# users in channel>,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": true
}
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

pubnub.Subscribe()
.Channels(new List<string> (){"foo.*"})
.Execute();
Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

Dictionary<string, object> state = new Dictionary<string, object>();
state.Add("k", "v");
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";

pubnub = new PubNub(pnConfiguration);
pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if (mea.Status != null) {
if (mea.Status.Category.Equals(PNStatusCategory.PNConnectedCategory)) {
pubnub.SetPresenceState()
.ChannelGroups(channelGroupList)
.State(state)
show all 35 lines
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.Subscribe()
.ChannelGroups(new List<string> (){"my_channel_group"})
.Execute();
Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.Subscribe()
.ChannelGroups(new List<string> (){"family"})
.WithPresence()
.Execute();

Unsubscribe

Description

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Unsubscribe from a channel you can use the following method(s) in the Unity V4 SDK:

pubnub.Unsubscribe().ChannelGroups(List<string>).Channels(List<string>).QueryParam(Dictionary<string,string>).Async(Command)
ParameterTypeRequiredDescription
ChannelGroupsList<string>OptionalUnsubscribe to channel groups, Either channel or channelGroup is required.
ChannelsList<string>OptionalUnsubscribe to channels, Either channel or channelGroup is required.
QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
AsyncCommandYesCommand that will execute unsubscribe.

Basic Usage

Unsubscribe from a channel:

pubnub.Unsubscribe()
.ChannelGroups(new List<string>(){
"my_channel_group"
})
.Channels(new List<string>() {
"my_channel"
})
.Async((result, status) => {
if (status.Error) {
Debug.Log(string.Format("Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log(string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
}
});
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Rest Response from Server

The Unsubscribe() operation returns a PNLeaveRequestResult which contains the following operations:

MethodTypeDescription
MessagestringThe message from the operation.

Other Examples

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.Unsubscribe()
.Channels(new List<string> (){"my_channel1", "my_channel2"})
.Async((result, status) => {

if(status.Error){
Debug.Log (string.Format("In Example, Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log (string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
}
});

Example Response

MethodTypeDescription
MessagestringThe message from the operation.

Unsubscribe from a channel group

pubnub.Unsubscribe()
.ChannelGroups(new List<string> (){"my_channel_group", "my_channel_group_1"})
.Async((result, status) => {

if(status.Error){
Debug.Log (string.Format("Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log (string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
}
});

Example Response

MethodTypeDescription
MessagestringThe message from the operation.

Unsubscribe All

Description

Unsubscribe from all channels and all channel groups

Method(s)

pubnub.UnsubscribeAll().QueryParam(Dictionary<string,string>).Async(Command)
ParameterTypeRequiredDescription
QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
AsyncCommandYesCommand that will unsubscribe from all subscribed channels.

Basic Usage

pubnub.UnsubscribeAll()
.Async((result, status) => {
if(status.Error){
Debug.Log (string.Format("UnsubscribeAll Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log (string.Format("DateTime {0}, In UnsubscribeAll, result: {1}", DateTime.UtcNow, result.Message));
}
});

Returns

None

Last updated on