On this page

Publish/Subscribe API for C# SDK

PubNub's global publisher latency is approximately 2 ms for a publish request to be processed and acknowledged. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level details on publishing and subscribing, refer to Connection Management and to Publish Messages. This page uses the C# software development kit (SDK) and application programming interfaces (APIs) to show how to publish and subscribe.

Request execution

Use try/catch when working with the C# SDK.

If a request has invalid parameters (for example, a missing required field), the SDK throws an exception. If the request reaches the server but fails (server error or network issue), the error details are available in the returned status.

1try
2{
3 PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
4 .Message("Why do Java developers wear glasses? Because they can't C#.")
5 .Channel("my_channel")
6 .ExecuteAsync();
7
8 PNStatus status = publishResponse.Status;
9
10 Console.WriteLine("Server status code : " + status.StatusCode.ToString());
11}
12catch (Exception ex)
13{
14 Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
15}

Publish

publish() sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.

  • Initialize PubNub with the publishKey.
  • You don't need to subscribe to publish to a channel.
  • You can't publish to multiple channels at the same time.

Method(s)

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

1pubnub.Publish()
2 .Message(object)
3 .Channel(string)
4 .ShouldStore(bool)
5 .Meta(Dictionary<string, object>)
6 .UsePOST(bool)
7 .Ttl(int)
8 .QueryParam(Dictionary<string,object>)
9 .CustomMessageType(string)
* required
ParameterDescription
Message *
Type: object
The payload.
Channel *
Type: string
Destination of the Message (channel ID).
ShouldStore
Type: bool
Store in history.
If ShouldStore is not specified, then the history configuration on the key is used.
Meta
Type: Dictionary<string, object>
Meta data object which can be used with the filtering ability.
UsePOST
Type: bool
If true, uses HTTP POST to publish the message. The message is sent in the request body instead of the query string (used with HTTP GET). Use POST for larger messages to avoid URL length limitations. Default: false.
Ttl
Type: int
Set 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 unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal.
  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.
QueryParam
Type: Dictionary<string, object>
Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
CustomMessageType
Type: string
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
Type: Command
Block the thread, exception thrown if something goes wrong.

This parameter is deprecated and will be removed in a future version. Please use the Execute parameter instead.
Async
Type: PNCallback
PNCallback of type PNPublishResult.

This parameter is deprecated and will be removed in a future version. Please use the ExecuteAsync parameter instead.
Execute
Type: PNCallback
PNCallback of type PNPublishResult.
ExecuteAsync
Type: None
Returns Task<PNResult<PNPublishResult>>.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.

Publish a message to a channel

1

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 PNResult<PNPublishResult> which contains the following properties:

Property NameTypeDescription
Result
PNPublishResult
Returns a PNPublishResult object.
Status
PNStatus
Returns a PNStatus object.

PNPublishResult contains the following properties:

Property NameTypeDescription
Timetoken
long
Returns a long representation of the timetoken when the message was published.

Other examples

Publish a message to a channel synchronously

1

Publish with metadata

1

Store the published message for 10 hours

1

Publish a Mobile Push payload

1

For more details, refer to Mobile Push.

Fire

The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.

Method(s)

To Fire a message you can use the following method(s) in the C# SDK:

1pubnub.Fire()
2 .Message(object)
3 .Channel(string)
4 .Meta(Dictionary<string, object>)
5 .UsePOST(bool)
6 .QueryParam(Dictionary<string,object>)
* required
ParameterDescription
Message *
Type: object
The payload.
Channel *
Type: string
Destination of the message (channel ID).
Meta
Type: Dictionary<string, object>
Meta data object which can be used with the filtering ability.
UsePOST
Type: bool
If true, uses HTTP POST to send the message. The message is sent in the request body instead of the query string (used with HTTP GET). Use POST for larger messages to avoid URL length limitations. Default: false.
QueryParam
Type: Dictionary<string, object>
Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
Sync
Type: Command
Block the thread, exception thrown if something goes wrong.

This parameter is deprecated and will be removed in a future version. Please use the Execute parameter instead.
Async
Type: PNCallback
PNCallback of type PNPublishResult.

This parameter is deprecated and will be removed in a future version. Please use the ExecuteAsync parameter instead.
Execute
Type: PNCallback
PNCallback of type PNPublishResult.
ExecuteAsync
Type: None
Returns Task<PNResult<PNPublishResult>>.

Sample code

Fire a message to a channel

1

Signal

The signal() function sends a signal to all subscribers of a channel.

Signals have a payload limit of 64 bytes. The limit applies to the payload, not the URI or headers. For a larger payload, contact support.

Method(s)

To Signal a message you can use the following method(s) in the C# SDK:

1pubnub.Signal()
2 .Message(object)
3 .Channel(string)
4 .CustomMessageType(string)
* required
ParameterDescription
Message *
Type: object
The payload.
Channel *
Type: string
Destination of the Message (channel ID).
CustomMessageType
Type: string
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.

Sample code

Signal a message to a channel

1

Response

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

Subscribe

The subscribe function opens a TCP socket to PubNub. It then listens for messages and events on a specified SDK entity or set of SDK entities. To subscribe, configure the appropriate subscribeKey during initialization.

Conceptual overview

For more general information about subscriptions, refer to Subscriptions.

SDK entities are first-class citizens that provide access to their encapsulated application programming interfaces (APIs). You can subscribe using the PubNub client object or directly on a specific SDK entity:

A newly subscribed client receives messages after the subscribe() call completes.

Subscription scope

Subscription objects let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:

  • Subscription: created from an SDK entity and scoped to that SDK entity (for example, a particular channel)
  • SubscriptionSet: created from the PubNub client and scoped to the client (for example, all subscriptions created on a single pubnub object). A set can include one or more subscriptions.

The event listener is a single point through which your app receives all the messages, signals, and events in the SDK entities you subscribed to. For information on adding event listeners, refer to Event listeners.

Create a subscription

An entity-level Subscription receives messages and events only for the SDK entity used to create it. Use multiple entity-level Subscriptions to handle different message or event types per 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 create a Subscription or SubscriptionSet and don't keep a strong reference, the .NET garbage collector (GC) may collect it after your code finishes executing, and you will stop receiving updates.

// SDK entity-based, local-scoped
Channel firstChannel = pubnub.Channel("first");

Subscription subscription = firstChannel.Subscription(SubscriptionOptions options);
* required
ParameterDescription
options
Type: SubscriptionOptions
Subscription behavior configuration.

Create a subscription set

A client-level SubscriptionSet receives messages and events across all SDK entities. Use a single SubscriptionSet to handle similar message or event types across channels.

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 create a Subscription or SubscriptionSet and don't keep a strong reference, the .NET garbage collector (GC) may collect it after your code finishes executing, and you will stop receiving updates.

// client-based, general-scoped
SubscriptionSet subscriptionSet = pubnub.SubscriptionSet(
channels: string[],
channelGroups: string[],
options: SubscriptionOptions
)
* required
ParameterDescription
channels *
Type: string[]
One or more channels to create a subscription of. Either channels or channelGroups is required.
channelGroups *
Type: string[]
One or more channels to create a subscription of. Either channels or channelGroups is required.
options
Type: SubscriptionOptions
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:

OptionDescription
ReceivePresenceEvents
Whether presence updates for userIds should be delivered through the listener streams.

For information on how to receive presence events and what those events are, refer to Presence Events.

Method(s)

Subscription and SubscriptionSet use the same subscribe<object>() method.

Subscribe

To subscribe, you can use the following method in the C# SDK:

subscription.Subscribe<object>(SubscriptionCursor cursor)
* required
ParameterDescription
cursor
Type: SubscriptionCursor
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.
Sample code
1

Other examples
Create a subscription set from two subscriptions
1

Returns

The subscribe() method doesn't have a return value.

SDK entities

SDK entities (also called entity handles) are subscribable objects for which you can receive real-time updates (messages, events, etc). An SDK entity is a local client-side handle: creating one performs no network call and does not require a matching server-side record to exist.

SDK entity is not the same as a DataSync entity

An SDK entity is the local handle described in this section. A DataSync entity is a stored server-side record, the source of truth for your application state, managed through the DataSync API.

The C# SDK ships no dedicated DataSync SDK entity. To observe a DataSync object, create a Channel SDK entity for the object's data channel and attach a DataSync listener to the resulting Subscription, a SubscriptionSet, or the PubNub client. Refer to Add DataSync listener.

Create channels

This method returns a local Channel SDK entity.

pubnub.Channel(String)
* required
ParameterDescription
Channel *
Type: String
The name of the channel to create a subscription of.

Sample code

1

Create channel groups

This method returns a local ChannelGroup SDK entity.

pubnub.ChannelGroup(String)
* required
ParameterDescription
ChannelGroup *
Type: String
The name of the channel group to create a subscription of.

Sample code

1

Create channel metadata

This method returns a local ChannelMetadata SDK entity.

pubnub.ChannelMetadata(String)
* required
ParameterDescription
ChannelMetadata *
Type: String
The String identifier of the channel metadata object to create a subscription of.

Sample code

1

Create user metadata

This method returns a local UserMetadata SDK entity.

pubnub.UserMetadata(String)
* required
ParameterDescription
UserMetadata *
Type: String
The String identifier of the user metadata object to create a subscription of.

Sample code

1

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.

No built-in event throttling

The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.

To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.

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)

1

Sample code

1

Add 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)

1pubnub.AddListener(listener)

Sample code

1

Returns

The subscription status. For information about available statuses, refer to SDK statuses.

Add DataSync listener

DataSync publishes an event when an object (a user, channel, membership, or a custom entity or relationship) is created, updated, or deleted. Both Set* and Update* calls fire the same update event, there's no separate patch event.

The delivery channel isn't always the id of the object that changed. A user, channel, or entity event reaches its own id channel, and an update or delete also reaches every connected entity's id channel. A membership or relationship event reaches the channels of both linked entities and never a channel named after the membership or relationship id. Refer to Where each event is delivered for the full mapping.

To receive them, create a Channel SDK entity for that channel, subscribe to it, and attach a listener.

Subclass SubscribeCallback and override the virtual DataSyncEvent(Pubnub pubnub, PNDataSyncEventResult dataSyncEvent) method, or construct a SubscribeCallbackExt with a dataSyncEventAction delegate. Pass the listener to subscription.AddListener() or subscriptionSet.AddListener() to scope it to those channels, or to pubnub.AddListener() to receive DataSync events across the client.

Choose the listener scope

Subscription and SubscriptionSet don't expose an onDataSync event property, but their inherited AddListener(SubscribeCallback) method accepts a callback that overrides DataSyncEvent. Use pubnub.AddListener() only when you want one listener to receive DataSync events from every subscribed channel on the client.

Events are off by default

To receive DataSync events, enable event publishing for the object's class in the Admin Portal. Refer to DataSync events for details.

Projections scope events

A change publishes one event per projection declared on the object's class. The object's own id channel carries the __default__ view of the payload, and each named projection is published to its own __<projection>__<id> channel carrying that projection's view. So subscribing to the object's id channel does not necessarily deliver every field. Refer to Projection channels.

Method(s)

To receive DataSync events, attach a listener through subscription.AddListener(), subscriptionSet.AddListener(), or pubnub.AddListener(). Construct a SubscribeCallbackExt with a dataSyncEventAction delegate for an inline callback, or subclass SubscribeCallback and override DataSyncEvent(Pubnub pubnub, PNDataSyncEventResult dataSyncEvent) for a full custom listener.

1

The listener callback receives a PNDataSyncEventResult with the following properties:

Property NameTypeDescription
Channel
string
The concrete data channel on which this copy arrived. It can be the changed object's id, a connected entity's id for a fanned-out event, or a named projection channel such as __admin__product-sneaker-42. Identify the changed object through EntityData.Id, RelationshipData.Id, or the top-level Id on a delete event.
Subscription
string
The subscription match, such as a wildcard pattern or channel group, if it differs from Channel.
Timestamp
long
The publish timetoken.
Version
string
The DataSync event schema version, currently 1.0.
Event
string
The change type: create, update, or delete.
Source
string
Always data-sync (hyphenated). This is the backend's wire-format value and differs intentionally from the DataSync naming used elsewhere in the SDK.
Type
string
The object kind: user, channel, membership, entity, or relationship. The built-in User, Channel, and Membership classes report their own kind, and a class you define reports the generic entity or relationship.
ClassName
string
The class name of the changed object, for example User, Channel, Membership, or one of your own.
ClassVersion
int
The class version of the changed object.
ClassLevel
string
The class hierarchy level, Global or SubKey. Read it alongside ClassName to tell a built-in class from one of your own that happens to share its name.
EntityData
PNDataSyncEntityResult
Populated when Type is entity, user, or channel, and Event is create or update.
RelationshipData
PNDataSyncRelationshipResult
Populated when Type is relationship or membership, and Event is create or update.
Id
string
Populated for delete events.
DeletedAt
string
Populated for delete events.

EntityData and RelationshipData carry the object's state at the time of the event:

Property NameTypeDescription
Id
string
The object's id.
EntityClass / RelationshipClass
string
The class name, on EntityData or RelationshipData respectively.
EntityClassVersion / RelationshipClassVersion
int
The class version.
EntityAId
string
Present only on RelationshipData. The linked id on the A side, which is the channel id on a membership event.
EntityBId
string
Present only on RelationshipData. The linked id on the B side, which is the user id on a membership event.
Status
string
The object's status, present only when the class declares Status under the projection this event was published on (falling back to __default__ when the class never declares it).
Payload
Dictionary<string, object>
The object's payload, filtered down to the fields the class declares under the projection this event was published on.
CreatedAt
string
Creation timestamp. Never filtered by projection.
UpdatedAt
string
Last update timestamp. Never filtered by projection.
ETag
string
The object's current ETag. Never filtered by projection.
ExpiresAt
string
Expiration timestamp, if set. Server-managed, there's no Create*/Update* parameter to set it from the SDK. Never filtered by projection.

The shape of the event depends on the object kind and the change type:

  • Entity events (users, channels, and custom entities) on create and update carry EntityData with the current object state.
  • Relationship events (memberships and custom relationships) on create and update carry RelationshipData with the same fields plus EntityAId and EntityBId, and RelationshipClass/RelationshipClassVersion in place of the entity class fields.
  • Delete events carry only Id and DeletedAt on the PNDataSyncEventResult itself, for both entities and relationships. Neither EntityData nor RelationshipData is populated.

For membership events, EntityAId is the channel id and EntityBId is the user id. The service sends these two as channelId and userId, and the SDK maps them onto the A and B sides so that PNDataSyncRelationshipResult serves both memberships and your own relationships. A membership event therefore does not carry the UserId and ChannelId properties you get back from GetMembership, even though the underlying event does name the ids that way.

EntityClass and EntityClassVersion on EntityData (and RelationshipClass and RelationshipClassVersion on RelationshipData) are populated from the event's own ClassName and ClassVersion. EntityClassLevel is not populated on event data, read ClassLevel on the event instead.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

To keep a full local copy of the object, fetch it once with pubnub.DataSync.GetEntity(...) for the current state, then apply events as they arrive. Compare the ETag or UpdatedAt on each event against your local copy to detect stale updates, for example:

1

For the fetch methods, refer to DataSync API. For the concurrency pattern, refer to the ETags concept documentation.

Unsubscribe

Stop receiving real-time updates from a Subscription or a SubscriptionSet.

Method(s)

subscription.Unsubscribe<object>()

subscriptionSet.Unsubscribe<object>()

Sample code

1

Returns

None

Unsubscribe all

Stop receiving real-time updates from all data streams and remove the SDK entities associated with them.

Client scope

This method is only available on the PubNub object.

Method(s)

1pubnub.UnsubscribeAll<object>()

Sample code

1

Returns

None

Subscribe (old)

Not recommended

The use of this method is discouraged. Use Subscribe instead.

Receive messages (old)

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 (old)

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 ID. To subscribe to a channel ID 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 ID 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) (old)

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

1pubnub.Subscribe<string>()
2 .Channels(Array)
3 .ChannelGroups(Array)
4 .WithTimetoken(long)
5 .WithPresence()
6 .QueryParam(Dictionary<string,object>)
7 .Execute()
* required
ParameterDescription
Channels
Type: Array
Subscribe to Channels, Either Channels or ChannelGroups is required.
ChannelGroups
Type: Array
Subscribe to ChannelGroups, Either Channels or ChannelGroups is required.
WithTimetoken
Type: long
Pass a Timetoken.
WithPresence
Type: Command
Also subscribe to related presence information.
QueryParam
Type: Dictionary<string, object>
Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
Execute *
Type: Command
Command that will Execute Subscribe.

Sample code (old)

Subscribe to a channel:

1

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 (old)

PNMessageResult

PNMessageResult<T> is returned in the Listeners

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

Property NameTypeDescription
Category
PNStatusCategory
Details of PNStatusCategory.
Error
bool
This is true if an error occurred in the execution of the operation.
ErrorData
PNErrorData
Error data of the exception (if Error is true)
StatusCode
int
Status code of the excution.
Operation
PNOperationType
Operation type of the request.
AffectedChannels
List<string>
A list of affected channels in the operation.
AffectedChannelGroups
List<string>
A list of affected channel groups in the operation.

The Subscribe() operation returns a PNMessageResult<T> for messages which contains the following operations:

Property NameTypeDescription
Message
object
The message sent on the channel ID.
Subscription
string
The channel group or wildcard subscription match (if exists).
Channel
string
The channel ID for which the message belongs.
Timetoken
long
Timetoken for the message.
UserMetadata
object
User metadata.

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

Property NameTypeDescription
Event
string
Events like join, leave, timeout, state-change, interval.
Uuid
string
UUID for the event.
Timestamp
long
Timestamp for the event.
Occupancy
int
Current occupancy.
State
Dictionary
State of the UUID.
Subscription
string
The channel group or wildcard subscription match (if exists).
Channel
string
The channel ID for which the message belongs.
Timetoken
long
Timetoken of the message.
UserMetadata
object
User metadata.
Join
string[]
List of channels when the event is interval.
Timeout
string[]
List of channels when the event is interval.
Leave
string[]
List of channels when the event is interval.
HereNowRefresh
bool
Flag to indicate whether HereNow fetch is needed.

Other examples (old)

Basic subscribe with logging

1

Subscribing to multiple channels

Subscribe to multiple channels using Multiplexing. The example uses an array of 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.

1

Subscribing to a Presence channel
Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

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.

1

Sample Responses (old)
Join event (old)
1{
2 "Event": "join",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": 1345546797,
5 "Occupancy": 2,
6 "State": null,
7 "Channel":" my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": null,
12 "Timeout": null,
13 "Leave": null,
14 "HereNowRefresh": false
15}
Leave event (old)
1{
2 "Event": "leave",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": 1345546797,
5 "Occupancy": 1,
6 "State": null,
7 "Channel": "my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": null,
12 "Timeout": null,
13 "Leave": null,
14 "HereNowRefresh": false
15}
Timeout event (old)
1{
2 "Event": "timeout",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": 1345546797,
5 "Occupancy": 0,
6 "State": null,
7 "Channel": "my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": null,
12 "Timeout": null,
13 "Leave": null,
14 "HereNowRefresh": false
15}
State change event (old)
1{
2 "Event": "state-change",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": 1345546797,
5 "Occupancy": 1,
6 "State": {
7 "isTyping": true
8 },
9 "Channel": "my_channel",
10 "Subscription": "",
11 "Timetoken": 15034141109823424,
12 "UserMetadata": null,
13 "Join": null,
14 "Timeout": null,
15 "Leave": null,
show all 17 lines
Interval event (old)
1{
2 "Event": "interval",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": <unix timestamp>,
5 "Occupancy": <# users in channel>,
6 "State": null,
7 "Channel": "my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": null,
12 "Timeout": null,
13 "Leave": null,
14 "HereNowRefresh": false
15}

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:

1{
2 "Event": "interval",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": <unix timestamp>,
5 "Occupancy": <# users in channel>,
6 "State": null,
7 "Channel": "my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": ["uuid2", "uuid3"],
12 "Timeout": ["uuid1"],
13 "Leave": null,
14 "HereNowRefresh": false
15}

If the full interval message is greater than 30 KB (since the max publish payload is ∼32 KiB), 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.

1{
2 "Event": "interval",
3 "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
4 "Timestamp": <unix timestamp>,
5 "Occupancy": <# users in channel>,
6 "State": null,
7 "Channel": "my_channel",
8 "Subscription": "",
9 "Timetoken": 15034141109823424,
10 "UserMetadata": null,
11 "Join": null,
12 "Timeout": null,
13 "Leave": null,
14 "HereNowRefresh": true
15}
Wildcard subscribe to channels (old)
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 (.).

1

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.*.

Subscribing with state (old)
Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

Required User ID

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.

1

Subscribe to a channel group (old)
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.

1

Subscribe to the Presence channel of a channel group (old)
Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Subscribe with a custom type (old)

C# supports subscribing with custom types. However only one type of message can be subscribed for a given channel. If you want to subscribe different types of messages for the same channel, then subscribing using the generic type as string is the recommended option.

1

Event listeners (old)

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

Method 1 to add listener (old)
1

Method 2 to add listener (old)
1

Remove listeners (old)
1

Listener status events (old)
CategoryDescription
PNNetworkIssuesCategory
The SDK is not able to reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNUnknownCategory
PubNub SDK could return this Category if the captured error is insignificant client side error or not known type at the time of SDK development.
PNBadRequestCategory
PubNub C# SDK will send PNBadRequestCategory when some parameter is missing like subscribe key, publish key.
PNTimeoutCategory
Processing has failed because of request time out.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).

Unsubscribe (old)

Not recommended

The use of this method is discouraged. Use Unsubscribe instead.

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) (old)

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

1pubnub.Unsubscribe<string>()
2 .Channels(Array)
3 .ChannelGroups(Array)
4 .QueryParam(Dictionary<string,object>)
5 .Execute()
* required
ParameterDescription
Channels
Type: Array
Unsubscribe to channels, Either Channels or ChannelGroups is required
ChannelGroups
Type: Array
Unsubscribe to channel groups, Either channels or channelGroup is required
QueryParam
Type: Dictionary<string, object>
Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
Execute *
Type: Command
Command that will execute Unsubscribe.

Sample code (old)

Unsubscribe from a channel:

1

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.

Response (old)

The Unsubscribe() operation returns a PNStatus. The output below demonstrates the response to a successful call:

1{
2 "Category": "PNDisconnectedCategory",
3 "ErrorData": null,
4 "Error": false,
5 "StatusCode": 200,
6 "Operation": "PNUnsubscribeOperation",
7 "TlsEnabled": false,
8 "Uuid": null,
9 "AuthKey": null,
10 "Origin": "ps.pndsn.com",
11 "ClientRequest": null,
12 "AffectedChannels": ["my_channel"],
13 "AffectedChannelGroups": []
14}

Other examples (old)

Unsubscribing from multiple channels (old)
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.

1

Example response (old)
1{
2 "Category": "PNDisconnectedCategory",
3 "ErrorData": null,
4 "Error": false,
5 "StatusCode": 200,
6 "Operation": "PNUnsubscribeOperation",
7 "TlsEnabled": false,
8 "Uuid": null,
9 "AuthKey": null,
10 "Origin": "ps.pndsn.com",
11 "ClientRequest": null,
12 "AffectedChannels": ["ch1","ch2","ch3"],
13 "AffectedChannelGroups": ["cg1","cg2","cg3"]
14}
Unsubscribe from a channel group (old)
1

Example response (old)
1{
2 "Category": "PNDisconnectedCategory",
3 "ErrorData": null,
4 "Error": false,
5 "StatusCode": 200,
6 "Operation": "PNUnsubscribeOperation",
7 "TlsEnabled": false,
8 "Uuid": null,
9 "AuthKey": null,
10 "Origin": "ps.pndsn.com",
11 "ClientRequest": null,
12 "AffectedChannels": [],
13 "AffectedChannelGroups": ["cg1","cg2","cg3"]
14}

Unsubscribe all (old)

Not recommended

The use of this method is discouraged. Use Unsubscribe All instead.

Unsubscribe from all channels and all channel groups

Method(s) (old)

1pubnub.UnsubscribeAll<string>()
2 .QueryParam(Dictionary<string,object>)
* required
ParameterDescription
QueryParam
Type: Dictionary<string, object>
Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.

Sample code (old)

1

Returns (old)

None