Publish/Subscribe API for PubNub Ruby 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

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 publish_key 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 Ruby 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, check 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 (for example, [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs, for example, 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 Ruby SDK:

publish(
channel: channel,
message: message,
store: store,
compressed: compressed,
publish_key: publish_key,
http_sync: http_sync,
callback: callback
)
ParameterTypeRequiredDescription
channelStringYesSpecify the channel name to publish the messages.
messageObjectYesSerializable object that has defined #to_json method.
storeBooleanOptionalSpecifies if message should be stored for history.Default true.
compressedBooleanOptionalSpecifies if message should be compressed.Default false.
publish_keyStringOptionalSpecifies the required publish_key to use to send messages to a channel.
http_syncBooleanOptionalDefault false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).
For sync methods Envelope object will be returned.
callbackLambda accepting one parameterOptionalCallback that will be called for each envelope.
For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Basic Usage

Publish a message to a channel

pubnub.publish(
channel: 'my_channel',
message: { text: 'Hi!' }
) do |envelope|
puts envelope.status
end
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.

Rest Response from Server

The function returns the following formatted response:

[1, "Sent", "13769558699541401"]

Other Examples

Publish a JSON serialized message

pubnub.publish(
message: {
key: {
inner_key: :value
}
},
channel: :whatever
)

Skip message from storage

pubnub.publish(message: 'Not gonna store that', store: false)

Fire

The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.

Method(s)

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

fire(
channel: channel,
message: message,
compressed: compressed,
publish_key: publish_key,
http_sync: http_sync,
callback: callback
)
ParameterTypeRequiredDescription
channelStringYesSpecify the channel name to publish the messages.
messageObjectYesSerializable object that has defined #to_json method.
compressedBooleanOptionalSpecifies if message should be compressed.Default false.
publish_keyStringOptionalSpecifies the required publish_key to use to send messages to a channel.
http_syncBooleanOptionalDefault false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).
For sync methods Envelope object will be returned.
callbackLambda accepting one parameterOptionalCallback that will be called for each envelope.
For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Basic Usage

Fire a message to a channel

pubnub.fire(
channel: 'my_channel',
message: {
text: 'Hi!'
}
) do |envelope|
puts envelope.status
end

Signal

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

pubnub.signal(
message: message,
channel: channel,
compressed: compressed
)
ParameterTypeRequiredDescription
messageObjectYesSerializable object that has defined #to_json method.
channelStringYesSpecify the channel name to send the messages.
compressedBooleanOptionalSpecifies if message should be compressed. Default false.

Basic Usage

Signal a message to a channel

pubnub.signal(
channel: 'foo',
message: {
msg: 'Hello Signals'
}
);

Rest Response from Server

The function returns the following formatted response:

[1, "Sent", "13769558699541401"]

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 subscribe_key at initialization. By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.

Connectivity notification

You can be notified of connectivity via the envelope.status. By waiting for the envelope.status to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

Using Ruby SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.

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

subscribe(
channels: channels,
channel_groups: group,
presence: presence,
presence_callback: presence_callback,
with_presence: with_presence,
http_sync: http_sync,
callback: callback
)
ParameterTypeRequiredDescription
channelsString, Symbol, ArrayOptionalSpecify the channels to subscribe to. It is possible to specify multiple channels as an array. It is possible to subscribe to wildcard channels.
channel_groupsString, Symbol, ArrayOptionalSpecifies the group to subscribe to. It is possible to specify multiple groups as an array.
presenceString, Symbol, ArrayOptionalSpecifies the channel to presence subscribe to. It is possible to specify multiple channels as an array.
presence_callbackLambda accepting one argumentOptionalCallback that is called for each presence event from wildcard subscribe. Works only with http_sync set to true.
with_presenceBooleanOptionalSubscribes to all presence channels of channels listed in channels parameter.
http_syncBooleanOptionalDefault false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).
For sync methods they will return array of Envelopes - envelope object for each message.
callbackLambda accepting one parameterOptionalCallback that is called for each retrieved message. Works only with http_sync set to true.
Event listeners

The response of the subscription is handled by Listener. Please see the Listeners section for more details.

Basic Usage

Subscribe to a channel:

# Subscribe to channel 'my_channel'.
pubnub.subscribe(
channels: :my_channel
)

Rest Response from Server

The output below demonstrates the response format to a successful call:

[[], "Time Token"]

Other Examples

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.

# Subscribe to channels (with presence) and groups
pubnub.subscribe(
channels: ['debug', 'info', 'warn'],
channel_groups: ['ruby_group', 'jruby_group', 'rbx_group'],
presence: ['debug', 'info', 'warn']
)
# You will be subscribed to channels: debug, info, warn, debug-pnpres, info-pnpres and warn-pnpres
# and to groups: ruby_group, jruby_group, rbx_group.

Subscribing to a Presence channel

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.

# Subscribes to room0, room0-pnpres, room1, room1-pnpres, room2, room2-pnpres
pubnub.subscribe(
channels: ['room0', 'room1', 'room2'],
with_presence: true
)

Sample Responses

Join Event

{
"action": "join",
"timestamp": 1345546797,
"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy": 2
}
Leave Event
{
"action" : "leave",
"timestamp" : 1345549797,
"uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy" : 1
}
Timeout Event
{
"action": "timeout",
"timestamp": 1345549797,
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"occupancy": 0
}
Custom Presence Event (State Change)
{
"action": "state-change",
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"timestamp": 1345549797,
"data": {
"isTyping": true
}
}
Interval Event
{
"action":"interval",
"timestamp":1474396578,
"occupancy":2
}

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:

{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"joined" : ["uuid2", "uuid3"],
"timedout" : ["uuid1"]
}

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.

{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"here_now_refresh" : true
}

Wildcard subscribe to channels

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

# Subscribe to wildcard channel 'ruby.*' (make sure you have wildcard subscribe enabled in your pubnub admin console!)
# specify two different callbacks for messages from channels and presence events in channels.
pubnub.subscribe(
channels: 'ruby.*'
)
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

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 UserId

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

require 'pubnub'

PUBKEY = 'demo'
SUBKEY = 'demo'

pubnub = Pubnub.new(
subscribe_key: SUBKEY,
publish_key: PUBKEY,
ssl: true
)

callback = Pubnub::SubscribeCallback.new(
message: ->(envelope) {
puts "MESSAGE: #{envelope.result[:data]}"
},
show all 32 lines

Subscribe to a channel group

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.

# Subscribe to group
pubnub.subscribe(
channel_groups: 'ruby_group'
)

Subscribe to the presence channel of a channel group

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

pubnub = Pubnub.new(
subscribe_key: :demo,
publish_key: :demo
)

callback = Pubnub::SubscribeCallback.new(
message: ->(_envelope) {
},
presence: ->(envelope) {
puts "PRESENCE: #{envelope.result[:data]}"
},
status: ->(_envelope) {
}
)

show all 18 lines
Subscribe Sync
Loop

The loop will exit when there is no subscribed channel left, closing the program in turn.

require 'pubnub'
pubnub = Pubnub.new(
subscribe_key: :demo,
publish_key: :demo
)

pubnub.subscribe(channels: :whatever)
while pubnub.subscribed_channels.size > 0 do
sleep 1
end

Unsubscribe

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

unsubscribe(
channels: channels,
channel_groups: group,
http_sync: http_sync,
callback: callback
)
ParameterTypeRequiredDescription
channelsSymbol, StringOptionalSpecify the channels to unsubscribe from. (Required if channel_groups is not specified)
channel_groupsSymbol, StringOptionalSpecify the channel_groups to unsubscribe from. (Required if channels is not specified)
http_syncBooleanOptionalDefault false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).
For sync methods Envelope object will be returned.
callbackLambda accepting one parameterOptionalCallback that will be called for each envelope.
For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Basic Usage

Unsubscribe from a channel:

pubnub.unsubscribe(
channel: 'my_channel'
) do |envelope|
puts envelope.status
end

Response

#<Pubnub::Envelope
@status = {
:code => 200,
:operation => :leave,
:category => :ack,
:error => false,
# [...]
},
# [...]
>

Other Examples

Unsubscribing from multiple channels

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.unsubscribe(
channel: ['chan1','chan2','chan3']
) do |envelope|
puts envelope.status
end
pubnub.unsubscribe(
channel: ['chan1','chan2','chan3']
) do |envelope|
puts envelope.result[:data][:messages]
end
Example Response
{
"action" : "leave"
}

Unsubscribing from a channel group

pubnub.leave(channel_group: "cg1") do |envelope|
puts envelope.status
end

Unsubscribing from multiple channel groups

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.leave(group: ["cg1", "cg2"]) do |envelope|
puts envelope
end
Last updated on