A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe below:

Publish/Subscribe API for JavaScript SDK

Publish/Subscribe API for JavaScript SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 30ms. 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.

Supported and recommended asynchronous patterns

PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the status errors, you must use the try...catch syntax in your code.

Publish

publish() sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel.

You can secure the messages with SSL/TLS by setting ssl to true during initialization. You can also encrypt messages.

The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. String content can include any single-byte or multi-byte UTF-8 characters.

Don't JSON serialize

You should not JSON serialize the message and meta parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.

The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.

If the message you publish exceeds the configured size, you receive a Message Too Large error. If you want to learn more or calculate your payload size, refer to Message Size Limit.

You can publish as fast as bandwidth conditions allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

You can optionally provide the customMessageType parameter to add your business-specific label or category to the message, for example text, action, or poll.

Method(s)

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

pubnub.publish({
message: any,
channel: string,
meta: any,
storeInHistory: boolean,
sendByPost: boolean,
ttl: number,
customMessageType: string
}): Promise<PublishResponse>;

* required

Parameter Description message *

Type: any

Default

:

n/a

The message may be any valid JSON type including objects, arrays, strings, and numbers. channel *

Type: string

Default

:

n/a

Specifies the channel ID to publish messages to. storeInHistory

Type: boolean

Default

:

true

If true the messages are stored in history.
If storeInHistory is not specified, then the history configuration on the key is used. sendByPost

Type: boolean

Default

:

false

When true, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages. Using HTTP POST to publish messages adheres to RESTful API best practices. meta

Type: any

Default

:

n/a

Publish extra meta with the request. ttl

Type: number

Default

:

n/a

Set a per message time to live in Message Persistence.
  1. If storeInHistory = true, and ttl = 0, the message is stored with no expiry time.
  2. If storeInHistory = 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 storeInHistory = 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.
customMessageType

Type: string

Default

:

n/a

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

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

Response
type PublishResponse = {
timetoken: number
}
Other examples Publish a JSON serialized message Store the published message for 10 hours Publish successful Publish unsuccessful by network down Publish unsuccessful by initialization without publishKey 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 JavaScript SDK:

fire({
Object message,
String channel,
Boolean sendByPost,
Object meta
})

* required

Parameter Description message *

Type: Object

Default

:

n/a

The message may be any valid JSON type including objects, arrays, strings, and numbers. channel *

Type: String

Default

:

n/a

Specifies channel ID to publish messages to. sendByPost

Type: Boolean

Default

:

false

If true the messages sent via POST. meta

Type: Object

Default

:

n/a

Publish extra meta with the request. Sample code Fire a message to a channel 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 JavaScript SDK:

pubnub.signal({
message: string,
channel: string,
customMessageType: string,
}): Promise<SignalResponse>;

* required

Parameter Description message *

Type: string

The message may be any valid JSON type including objects, arrays, strings, and numbers. channel *

Type: string

Specifies channel ID to send messages to. 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 Response
type SignalResponse = {
timetoken: number
}
Subscribe

The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey at initialization.

Conceptual overview

For more general information about subscriptions, refer to Subscriptions.

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

A newly subscribed client receives messages after the subscribe() call completes. You can configure retryConfiguration to automatically attempt to reconnect and retrieve any available messages if a client gets disconnected.

Subscribe only opens the connection

Calling subscribe() opens a connection but doesn't deliver messages to your code. You must also add event listeners to receive messages and access sender information. The message object received through listeners includes the sender's ID in the publisher field.

Subscription scope

Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:

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.

Add subscriptions to an existing set

If you subscribe to a subscription set and then add more subscriptions to it, they are automatically subscribed to.

Create a subscription

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


const channel = pubnub.channel('channel_1');
channel.subscription(subscriptionOptions)
Create a subscription set

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.


pubnub.subscriptionSet({
channels: string[],
channelGroups: string[],
subscriptionOptions: subscriptionOptions
}))

* required

Parameter Description  → channels

Type: string[]

Channels to subscribe to. Either channels or channelGroups is mandatory.  → channelGroups

Type: string[]

Channel groups to subscribe to. Either channels or channelGroups is mandatory.  → subscriptionOptions

Type: subscriptionOptions

Subscription behavior configuration. subscriptionOptions

subscriptionOptions is a class. Available properties include:

Option Type Description receivePresenceEvents boolean 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.

cursor object 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?: string; region?: number }

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.

Modify a subscription set

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

Refer to the Other examples section for more information on adding and removing subscriptions.

Method(s)

subscription and subscriptionSet use the same subscribe() method.

Subscribe

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

subscription.subscribe()
subscriptionSet.subscribe()
Sample code Wildcard subscribe and message objects

Wildcard subscribe (e.g., sports.*) works the same as regular subscribe - you still need to add event listeners to receive messages. The message objects received include the sender's ID in the publisher field, the actual channel name in the channel field, and the wildcard match in the subscription field.

Other examples Create a subscription set from 2 individual subscriptions Create a subscription set from 2 sets Add subscriptions to an existing set Returns

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

Entities

Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).

Create channels

This method returns a local channel entity.

* required

Parameter Description channel *

Type: string

The ID of the channel to create a subscription of. Sample code Create channel groups

This method returns a local channelGroup entity.

pubnub.channelGroup(string)

* required

Parameter Description channel_group *

Type: string

The name of the channel group to create a subscription of. Sample code Create channel metadata

This method returns a local channelMetadata entity.

pubnub.channelMetadata(string)

* required

Parameter Description channelMetadata *

Type: string

The String identifier of the channel metadata object to create a subscription of. Sample code Create user metadata

This method returns a local userMetadata entity.

pubnub.userMetadata(string)

* required

Parameter Description userMetadata *

Type: string

The String identifier of the user metadata object to create a subscription of. Sample code Event listeners

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

You can attach listeners to the instances of subscription, subscriptionSet, and, in the case of the connection status, the PubNub client.

Add listeners

You can implement multiple listeners with the addListener() method or register an event-specific listener that receives only a selected type, like message or file.

Method(s) Sample code Message object contains sender information

When you receive messages through listeners, the message object includes the sender's ID in the publisher field, along with the message content, channel name, timetoken, and other metadata.

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) Sample code Returns

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

Unsubscribe

Stop receiving real-time updates from a subscription or a subscriptionSet.

Method(s)
subscription.unsubscribe()

subscriptionSet.unsubscribe()
Sample code Returns

None

Unsubscribe all

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

Client scope

This method is only available on the PubNub object.

Method(s) Sample code Returns

None

Subscribe (old) Not recommended

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

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

Connectivity notification

You can be notified of connectivity via the listener, on establishing connection the statusEvent.category returns PNConnectedCategory.

By waiting for the connect event 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.

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

pubnub.subscribe({
channels: Array<string>,
channelGroups: Array<string>,
withPresence: boolean,
timetoken: number
}): Promise<SubscribeResponse>;

* required

Parameter Description channels *

Type: Array<string>

Default

:

n/a

Specifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array. channelGroups

Type: Array<string>

Default

:

n/a

Specifies the channelGroups to subscribe to. withPresence

Type: boolean

Default

:

false

If true it also subscribes to presence instances. timetoken

Type: number

Default

:

n/a

Specifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. Sample code

Subscribe to a channel:

Event listeners

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

Returns The following objects will be returned in the status response Object Description category PNConnectedCategory operation PNSubscribeOperation affectedChannels The channels affected in the operation, of type array. subscribedChannels All the current subscribed channels, of type array. affectedChannelGroups The channel groups affected in the operation, of type array. lastTimetoken The last timetoken used in the subscribe request, of type long. currentTimetoken The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}
The following objects will be returned in the subscribe message response Object Description channel The channel ID for which the message belongs. subscription The channel group or wildcard subscription match (if exists). timetoken Publish timetoken. message The payload. actualChannel Deprecated. Use property channel. subscribedChannel Deprecated. Use property subscription.
{
actualChannel: null,
channel: "my_channel_1",
message: "Hello World!",
publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
subscribedChannel: "my_channel_1",
subscription: null,
timetoken: "14966804541029440"
}
The following objects will be returned in the Presence response Object Description action Can be join, leave, state-change or timeout. channel The channel ID for which the message belongs. occupancy No. of users connected with the channel ID. state User State. subscription The channel group or wildcard subscription match (if exists) timestamp Current timetoken. timetoken Publish timetoken. uuid UUIDs of users who are connected with the channel ID.
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}
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.

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.

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

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

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

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 the presence channel of a channel group Requires Stream Controller and Presence add-ons

This method requires that 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.

Subscribing to 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.

Subscribing to a channel and channel group simultaneously 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.

Sample Responses Join event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "join",
"timetoken": "15119466699655811",
"occupancy": 2,
"uuid": "User1",
"timestamp": 1511946669
}
Leave event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "leave",
"timetoken": "15119446002445794",
"occupancy": 1,
"uuid": "User1",
"timestamp": 1511944600
}
Timeout event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "timeout",
"timetoken": "15119519897494311",
"occupancy": 3,
"uuid": "User2",
"timestamp": 1511951989
}
State change event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "state-change",
"state": {
"isTyping": true
},
"timetoken": "15119477895378127",
"occupancy": 5,
"uuid": "User4",
"timestamp": 1511947789
}
Interval event
{
"action": "interval",
"occupancy": 2,
"timestamp": 1511947739
}

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.

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

{
"action":"interval",
"timestamp":1548340678,
"occupancy":2,
"join":["pn-94bea6d1-2a9e-48d8-9758-f1b7162631ed","pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"]},
"timedout":["pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"],
"b":"my-channel-pnpres"
}

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.

{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "interval",
"timetoken": "15119477396210903",
"occupancy": 4,
"timestamp": 1511947739,
"here_now_refresh" : true
}

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

Listeners should be added before calling the method.

Add listeners
pubnub.addListener({

message: function (m) {
const channelName = m.channel;
const channelGroup = m.subscription;
const pubTT = m.timetoken;
const msg = m.message;
const publisher = m.publisher;
},


presence: function (p) {
const action = p.action;
const channelName = p.channel;
const occupancy = p.occupancy;
show all 72 lines Remove listeners
var existingListener = {
message: function () {
},
};

pubnub.removeListener(existingListener);
Listener status events Category Description PNNetworkUpCategory The SDK detected that the network is online. PNNetworkDownCategory The SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers. PNNetworkIssuesCategory A subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. This may be due to many reasons, such as the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy. PNReconnectedCategory The SDK was able to reconnect to PubNub. PNConnectedCategory SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. PNAccessDeniedCategory Access Manager permission failure. PNMalformedResponseCategory JSON parsing crashed. PNBadRequestCategory The server responded with a bad response error because the request is malformed. PNDecryptionErrorCategory If using decryption strategies and the decryption fails. PNTimeoutCategory Failure to establish a connection to PubNub due to a timeout. PNRequestMessageCountExceedCategory The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. PNUnknownCategory Returned when the subscriber gets a non-200 HTTP response code from the server. 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)

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

pubnub.unsubscribe({
channels: Array<string>,
channelGroups: Array<string>
}): Promise<UnsubscribeResponse>;

* required

Parameter Description channels *

Type: Array<string>

Specifies the channel ID to unsubscribe from. channelGroups

Type: Array<string>

Specifies the channelGroups to unsubscribe from. Sample code

Unsubscribe from a channel:

Response

The output below demonstrates the response to a successful call:

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.

Example response 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.

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) Sample code Returns

None


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4