Publish/Subscribe API for Unreal SDK

icon

Usage in Blueprints and C++


PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

Publish - Channel entity

icon

Available in entities

Channel

PublishMessage() 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.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel entity where you will publish to.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)

To publish to a channel, you must first create a Channel entity where you provide the name of the channel you want to publish to.

UPubnubChannelEntity* ChannelEntity = PubnubSubsystem->CreateChannelEntity("my-channel");

ChannelEntity->PublishMessage(
FString Message,
FOnPublishMessageResponse OnPublishMessageResponse,
FPubnubPublishSettings PublishSettings = FPubnubPublishSettings()
);
* required
ParameterDescription
Message *
Type: FString
The message to publish. Can be a literal string or JSON-formatted string containing serialized data.
OnPublishMessageResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnPublishMessageResponseNative to handle the result using a lambda.
PublishSettingsStruct defining publish configuration.

FPubnubPublishSettings

* required
ParameterDescription
StoreInHistory
Type: bool
Whether to store the message so it is available to be returned by the History API. true by default.
Ttl
Type: int
Time-to-live (TTL) for the message in hours. If not specified, the message will use the default retention period configured for the key.
MetaData
Type: FString
A JSON object containing additional (meta) data about the message which you can use with the filtering ability.
PublishMethod
Type: EPubnubPublishMethod
Which HTTP method to use for the publish transaction. Available values:

  • PPM_SendViaGET
  • PPM_SendViaPOST
  • PPM_UsePATCH
  • PPM_SendViaPOSTwithGZIP
  • PPM_UsePATCHwithGZIP
  • PPM_UseDELETE
Replicate
Type: bool
If true, the message is replicated and is received by all subscribers. If false, the message is not replicated and is delivered only to Functions event handlers.
CustomMessageType
Type: FString
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

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Publish a message to a channel

Actor.h



Actor.cpp



Subscribe to the channel

Before running the above publish example (either using the Debug Console or in a separate script running in a new terminal window), subscribe to the same channel that you publish the message to.

Returns

This function is void, but the delegate returns the FOnPublishMessageResponse struct.

FOnPublishMessageResponse

FieldTypeDescription
Result
FPubnubOperationResult
The result of the operation.
PublishedMessage
FPubnubMessageData
A struct containing the result of the operation.

FPubnubMessageData

FieldTypeDescription
Message
FString
The message itself.
Channel
FString
Channel that the message was published to.
UserID
FString
The message information about the publisher.
Timetoken
FString
The time token of the message, indicating when it was published.
Metadata
FString
The message metadata, as published.
MessageType
EPubnubMessageType
Indicates the message type: a signal, published, or another type.
CustomMessageType
FString
User-provided message type.
MatchOrGroup
FString
Subscription match or the channel group.
region
int
Region of the message. Not relevant in most cases.
flags
int
Message flags.

EPubnubMessageType

FieldDescription
PMT_Signal
Indicates that the message was received as a signal.
PMT_Published
Indicates that the message was published.
PMT_Action
Indicates an action on a published message.
PMT_Objects
Message about Objects.
PMT_Files
Message about Files.

FOnPublishMessageResponseNative

FieldTypeDescription
Result
const FPubnubOperationResult&
The result of the operation.
PublishedMessage
const FPubnubMessageData&
A struct containing the result of the operation.

Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Publish a message with settings

Actor.h


Actor.cpp


Publish a message with result

Actor.h


Actor.cpp


Publish - PubNub client

PublishMessage() 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.

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

Method(s)

PubnubSubsystem->PublishMessage(
FString Channel,
FString Message,
FOnPublishMessageResponse OnPublishMessageResponse,
FPubnubPublishSettings PublishSettings = FPubnubPublishSettings()
);
* required
ParameterDescription
Channel *
Type: FString
The channel ID to send the message to.
Message *
Type: FString
The message to publish. Can be a literal string or JSON-formatted string containing serialized data.
OnPublishMessageResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnPublishMessageResponseNative to handle the result using a lambda.
PublishSettingsStruct defining publish configuration.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Publish a message to a channel

Actor.h



Actor.cpp



Returns

This function is void, but the delegate returns the FOnPublishMessageResponse struct.

Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Publish a message with settings

Actor.h


Actor.cpp


Publish a message with result

Actor.h


Actor.cpp


Signal - Channel entity

icon

Available in entities

Channel

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

  • You must initialize PubNub with the publishKey.
  • You must create a Channel entity where you will signal to.
  • The message payload size (without the URI or headers) is limited to 64 bytes. If you require a larger payload size, contact support.

Method(s)

UPubnubChannelEntity* ChannelEntity = PubnubSubsystem->CreateChannelEntity("my-channel");

ChannelEntity->Signal(
FString Message,
FOnSignalResponse OnSignalResponse,
FPubnubSignalSettings SignalSettings = FPubnubSignalSettings()
);
* required
ParameterDescription
Message *
Type: FString
The message to publish. Can be a literal string or JSON-formatted string containing serialized data.
OnSignalResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSignalResponseNative to handle the result using a lambda.
SignalSettingsStruct defining signal configuration.

FPubnubSignalSettings

* required
ParameterDescription
CustomMessageType
Type: FString
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

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Signal a message to a channel

Actor.h



Actor.cpp



Returns

The delegate returns the FOnSignalResponse struct.

FOnSignalResponse

FieldTypeDescription
Result
FPubnubOperationResult
The result of the operation.
SignalMessage
FPubnubMessageData
A struct containing the result of the operation.

FOnSignalResponseNative

FieldTypeDescription
Result
const FPubnubOperationResult&
The result of the operation.
SignalMessage
const FPubnubMessageData&
A struct containing the result of the operation.

Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Signal with custom message type

Actor.h


Actor.cpp


Signal - PubNub client

Not recommended

The following approach to sending signals is not recommended. We recommend using the entity-based Signal approach.

The Signal() function sends 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, contact support.

  • You must initialize PubNub with the publishKey.
  • The message payload size (without the URI or headers) is limited to 64 bytes. If you require a larger payload size, contact support.

Method(s)

PubnubSubsystem->Signal(
FString Channel,
FString Message,
FOnSignalResponse OnSignalResponse,
FPubnubSignalSettings SignalSettings = FPubnubSignalSettings()
);
* required
ParameterDescription
Channel *
Type: FString
The channel ID to send the signal to.
Message *
Type: FString
The message to publish. Can be a literal string or JSON-formatted string containing serialized data.
OnSignalResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSignalResponseNative to handle the result using a lambda.
SignalSettingsStruct defining signal configuration.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Signal a message to a channel

Actor.h



Actor.cpp



Returns

This function is void, but the delegate returns the FOnSignalResponse struct.

Other examples

Signal with custom message type

Actor.h


Actor.cpp


Subscribe

Subscribe opens a TCP socket and listens for messages and events on a specified entity or set of entities. Set SubscribeKey during initialization.

Conceptual overview

For more general information about subscriptions, refer to Subscriptions.

Entities are first-class citizens that expose their APIs. You can subscribe using the PubNub client or directly on a specific entity:

After Subscribe(), the client receives new messages. Configure automatic reconnection handling through the PubNub subsystem.

Subscription scope

Subscriptions 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 entity and scoped to that 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 PubnubSubsystem 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 entities you subscribed to. For information on adding event listeners, refer to Event listeners.

Create a subscription

Managing subscription lifecycle

The subscription object lives independently from the entity and requires separate lifecycle management. The subscription will remain valid and functional even if the entity goes out of scope or is destroyed.

An entity-level Subscription allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscriptions is useful for handling various message/event types differently in each channel.

// Create entity
UPubnubChannelEntity* ChannelEntity = PubnubSubsystem->CreateChannelEntity("my-channel");

// Create subscription from entity
UPubnubSubscription* Subscription = ChannelEntity->CreateSubscription();
* required
ParameterDescription
SubscribeSettingsSettings for the subscription configuration.

FPubnubSubscribeSettings

* required
ParameterDescription
ReceivePresenceEvents
Type: bool
Whether to subscribe to presence events.

Create a subscription set

Managing subscription lifecycle

The subscription object lives independently from the entity and requires separate lifecycle management. The subscription will remain valid and functional even if the entity goes out of scope or is destroyed.

A client-level SubscriptionSet allows you to receive messages and events for all entities in the set. A single SubscriptionSet is useful for similarly handling various message/event types in each channel.

From channel or channel group names

You can create a subscription set from channel and channel group names.

PubnubSubsystem->CreateSubscriptionSet(Channels, ChannelGroups, SubscriptionSettings);
* required
ParameterDescription
Channels
Type: TArray<FString>
Array of channel names to include in the subscription set.
ChannelGroups
Type: TArray<FString>
Array of channel group names to include in the subscription set.
SubscriptionSettingsSettings for the subscription configuration.

From entities

You can create a subscription set from existing entities.

PubnubSubsystem->CreateSubscriptionSetFromEntities(Entities, SubscriptionSettings);
* required
ParameterDescription
Entities *
Type: TArray<UPubnubBaseEntity*>
Array of entities to include in the subscription set.
SubscriptionSettingsSettings for the subscription configuration.

Method(s)

Subscription and SubscriptionSet use the same methods to subscribe:

Subscribe

To subscribe, you can use the following methods:

// Subscribe to start receiving messages
Subscription->Subscribe();
// Subscribe to all entities in the set
SubscriptionSet->Subscribe();

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Subscribe to a channel
Actor.h


Actor.cpp


Subscribe with timetoken

You can subscribe with a specific timetoken to receive messages from that point in time.

// Subscribe with timetoken
FPubnubSubscriptionCursor Cursor;
Cursor.Timetoken = "15640261328790011";

Subscription->Subscribe(Cursor);
FPubnubSubscriptionCursor

| Parameter Type | Required | Description | | :---------- | :-------- | :------- | :------ | | Timetoken | FString | Yes | Timetoken from which messages should be retrieved. | | Region | int | No | Region of the messages. Set automatically; typically not required to set. |

Add subscriptions

You can add individual subscriptions to an existing set to create new sets. If you subscribe to a subscription set and then add more subscriptions, they are automatically subscribed to.

// Add individual subscription to set
UPubnubSubscription* NewSubscription = ChannelEntity->CreateSubscription();
SubscriptionSet->AddSubscription(NewSubscription);

Remove subscriptions

You can remove individual subscriptions from a subscription set.

// Remove subscription from set
SubscriptionSet->RemoveSubscription(NewSubscription);

Merge subscription sets

You can merge multiple subscription sets together.

// Merge subscription sets
SubscriptionSet1->AddSubscriptionSet(SubscriptionSet2);

Remove subscription sets

You can remove entire subscription sets from another set.

// Remove subscription set from another set
SubscriptionSet1->RemoveSubscriptionSet(SubscriptionSet2);

Other examples

Subscribe to a channel group

Actor.h

Actor.cpp

Subscribe to channel metadata

Actor.h

Actor.cpp

Subscribe to user metadata

Actor.h

Actor.cpp

Create subscription set from names

Actor.h

Actor.cpp

Create subscription set from entities

Actor.h

Actor.cpp

Manage subscriptions in a set

Actor.h

Actor.cpp

Merge subscription sets

Actor.h

Actor.cpp

Event listeners

Messages and events are received in your app using listeners. This listener allows a single point to receive all messages, signals, and events.

You can attach listeners to the instances of Subscription, SubscriptionSet.

Add listeners

You can add listeners for various types of updates related to your subscription. You can implement listeners for general updates (that handle multiple event types at once) or choose listeners dedicated to specific event types such as Message or Signal.

Catch all events

The OnAnyEventReceived listener catches all event types.

Handle multiple event types

You can add multiple event listeners to handle different types of events.

// Add message listener
Subscription->OnPubnubMessage.AddDynamic(this, &AMyActor::OnMessageReceived);

// Add signal listener
Subscription->OnPubnubSignal.AddDynamic(this, &AMyActor::OnSignalReceived);

// Add presence event listener
Subscription->OnPubnubPresenceEvent.AddDynamic(this, &AMyActor::OnPresenceEventReceived);

// Add object event listener
Subscription->OnPubnubObjectEvent.AddDynamic(this, &AMyActor::OnObjectEventReceived);

// Add message action listener
Subscription->OnPubnubMessageAction.AddDynamic(this, &AMyActor::OnMessageActionReceived);

show all 17 lines

Handle one event type with native callbacks

You can also use native callbacks that support lambda expressions.

// Add native callback listeners
Subscription->OnPubnubMessageNative.AddLambda([](const FPubnubMessageData& Message) {
UE_LOG(LogTemp, Log, TEXT("Message received: %s"), *Message.Message);
});

Subscription->OnPubnubSignalNative.AddLambda([](const FPubnubMessageData& Signal) {
UE_LOG(LogTemp, Log, TEXT("Signal received: %s"), *Signal.Message);
});

Remove event listener

To remove the listener for a specific event, assign nullptr to it or use RemoveAll() on the delegate.

// Remove specific listener
Subscription->OnPubnubMessage.RemoveDynamic(this, &AMyActor::OnMessageReceived);

// Remove all listeners for a specific event type
Subscription->OnPubnubMessage.RemoveAll(this);

Add connection status listener

Use the subscription status listener with your PubnubSubsystem instance to add a listener dedicated to connection status updates.

Client scope

This listener is only available on the PubNub object.

Method(s)

// Add subscription status listener
PubnubSubsystem->OnSubscriptionStatusChanged.AddDynamic(this, &AMyActor::OnSubscriptionStatusChanged);

Sample code

Actor.h




Actor.cpp



Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Subscribe with all event listeners

Actor.h

Actor.cpp

Add message listener with lambda

Actor.h

Actor.cpp

Add error listener

Actor.h

Actor.cpp

Add error listener with lambda

Actor.h

Actor.cpp

Returns

This method returns the subscription status and will emit various statuses depending on your client network connection.

For more information on connection management, refer to SDK Connection Lifecycle.

Other examples

Add connection status listener with lambda
// Add subscription status listener with lambda
PubnubSubsystem->OnSubscriptionStatusChangedNative.AddLambda([](EPubnubSubscriptionStatus Status) {
UE_LOG(LogTemp, Log, TEXT("Subscription status changed: %d"), (int32)Status);
});

Unsubscribe

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

Method(s)

// Unsubscribe from a subscription
Subscription->Unsubscribe();

// Unsubscribe from a subscription set
SubscriptionSet->Unsubscribe();

Sample code

Unsubscribe from a subscription

// Unsubscribe from a subscription
Subscription->Unsubscribe();

Unsubscribe from a subscription set

// Unsubscribe from all entities in the set
SubscriptionSet->Unsubscribe();

Returns

None

Unsubscribe all

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

Client scope

This method is only available on the PubNubSubsystem object.

Method(s)

PubnubSubsystem->UnsubscribeFromAll(FOnSubscribeOperationResponse OnUnsubscribeFromAllResponse);
* required
ParameterDescription
OnUnsubscribeFromAllResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

Actor.h



Actor.cpp



Returns

This method doesn't have a return value.

Subscribe (old)

Not recommended

The following approach to subscribing is not recommended. We recommend using the entity-based Subscribe approach.

Receive messages

Your app receives messages and events via event listeners. The OnMessageReceived 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 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.

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)

// subscribe to a channel
PubnubSubsystem->SubscribeToChannel(FString Channel, FOnSubscribeOperationResponse OnSubscribeToChannelResponse, FPubnubSubscribeSettings SubscribeSettings = FPubnubSubscribeSettings());
// subscribe to a channel group
PubnubSubsystem->SubscribeToGroup(FString ChannelGroup, FOnSubscribeOperationResponse OnSubscribeToGroupResponse, FPubnubSubscribeSettings SubscribeSettings = FPubnubSubscribeSettings());
* required
ParameterDescription
Channel *
Type: FString
The channel ID to subscribe to.
ChannelGroup *
Type: FString
The channel group to subscribe to.
OnSubscribeToChannelResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.
OnSubscribeToGroupResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.
SubscriptionSettingsStruct defining subscription configuration.
FOnSubscribeOperationResponse
FieldTypeDescription
Result
FPubnubOperationResult
The result of the operation.
FOnSubscribeOperationResponseNative
FieldTypeDescription
Result
const FPubnubOperationResult&
The result of the operation.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Actor.h


Actor.cpp


Event listeners

The response of the call is handled by adding a listener. Refer to the Event Listeners section for more details. Listeners should be added before calling the method.

Returns

This method doesn't have a return value. To receive messages, you must add a listener.

Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Subscribe with presence
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 or you can use the subscribe method with the ReceivePresenceEvents parameter set to true. For more information on presence events, refer to the Presence section.

Actor.h


Actor.cpp


Response

All presence events are received via a listener. For more information on the structure of the received events, refer to Event types.

Subscribe to channel group
Actor.h


Actor.cpp


Subscribe with lambda
Actor.h


Actor.cpp


Subscribe with result callback
Actor.h


Actor.cpp


Unsubscribe (old)

Not recommended

The following approach to unsubscribing is not recommended. We recommend using the entity-based Unsubscribe approach.

When subscribed to a single channel, this function causes the client to issue a leave from the channel ID 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)

// unsubscribe from a channel
PubnubSubsystem->UnsubscribeFromChannel(FString Channel, FOnSubscribeOperationResponse OnUnsubscribeFromChannelResponse);
// unsubscribe from a channel group
PubnubSubsystem->UnsubscribeFromGroup(FString ChannelGroup, FOnSubscribeOperationResponse OnUnsubscribeFromGroupResponse);
* required
ParameterDescription
Channel *
Type: FString
The channel ID to unsubscribe from.
ChannelGroup *
Type: FString
The channel group to unsubscribe from.
OnUnsubscribeFromChannelResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.
OnUnsubscribeFromGroupResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Actor.h


Actor.cpp


Returns

This method doesn't have a return value.

Other examples

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Unsubscribe from a channel group
Actor.h


Actor.cpp


Unsubscribe all (old)

Not recommended

The following approach to unsubscribing from all channels is not recommended. We recommend using the entity-based Unsubscribe approach.

Unsubscribe from all channels and all channel groups.

Method(s)

PubnubSubsystem->UnsubscribeFromAll(FOnSubscribeOperationResponse OnUnsubscribeFromAllResponse);
* required
ParameterDescription
OnUnsubscribeFromAllResponseThe delegate for the operation's result.

You can also use a native callback of the type FOnSubscribeOperationResponseNative to handle the result using a lambda.

Sample code

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.
Actor.h


Actor.cpp


Returns

This method doesn't have a return value.

Complete example

Reference code
Set up your Unreal project and follow the instructions in the lines marked with ACTION REQUIRED before running the code.

ASample_PubSubFull.h



ASample_PubSubFull.cpp



Last updated on