Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future. Before you go, please visit our GCM and FCM developer survey to give us feedback!

Implementing an XMPP Connection Server

The Google Cloud Messaging (GCM) Cloud Connection Server (CCS) is an XMPP endpoint that provides a persistent, asynchronous, bidirectional connection to Google servers. The connection can be used to send and receive messages between your server and your users' GCM-connected devices.

You can continue to use the HTTP request mechanism to send messages to GCM servers, side-by-side with CCS which uses XMPP. Some of the benefits of CCS include:

  • The asynchronous nature of XMPP allows you to send more messages with fewer resources.
  • Communication is bidirectional—not only can your server send messages to the device, but the device can send messages back to your server.
  • The device can send messages back using the same connection used for receiving, thereby improving battery life.

See the Server Reference for a list of all the message parameters and which connection server(s) supports them.

Establishing a Connection

CCS just uses XMPP as an authenticated transport layer, so you can use most XMPP libraries to manage the connection.

The CCS XMPP endpoint runs at gcm-xmpp.googleapis.com:5235. When testing functionality with non-production users, you should instead connect to gcm-preprod.googleapis.com:5236 (note the different hostname and port).

Regular testing on preprod (a smaller environment where the latest CCS builds run) is beneficial for isolating real users from test code. Test devices and test code connecting to gcm-preprod.googleapis.com:5236 should use a different GCM sender ID to avoid any risks of sending test messages to production users or sending upstream messages from production traffic over test connections.

The connection has two important requirements:

  • You must initiate a Transport Layer Security (TLS) connection. Note that CCS doesn't currently support the STARTTLS extension.
  • CCS requires a SASL PLAIN authentication mechanism using <your_GCM_Sender_Id>@gcm.googleapis.com (GCM sender ID) and the Server key as the password, where the sender ID and Server key are the values you gathered when configuring your client app. See the client documentation for your platform for information on obtaining these credentials.

If at any point the connection fails, you should immediately reconnect. There is no need to back off after a disconnect that happens after authentication.

For each sender ID, GCM allows 1000 connections in parallel.

Authentication

The following snippets illustrate how to perform authentication in CCS.

Client

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

Server

<stream:features>
  <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
    <mechanism>X-OAUTH2</mechanism>
    <mechanism>X-GOOGLE-TOKEN</mechanism>
    <mechanism>PLAIN</mechanism>
  </mechanisms>
</stream:features>

Client

<auth mechanism="PLAIN"
xmlns="urn:ietf:params:xml:ns:xmpp-sasl">MTI2MjAwMzQ3OTMzQHByb2plY3RzLmdjbS5hb
mFTeUIzcmNaTmtmbnFLZEZiOW1oekNCaVlwT1JEQTJKV1d0dw==</auth>

Server

<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>

Client

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

Server

<stream:features>
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
  <session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
</stream:features>

Client

<iq type="set">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"></bind>
</iq>

Server

<iq type="result">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
    <jid>SENDER_ID@gcm.googleapis.com/RESOURCE</jid>
  </bind>
</iq>

Note: CCS does not use the bound resource while routing messages.

Downstream Messages

Once the XMPP connection is established, CCS and your server use normal XMPP <message> stanzas to send JSON-encoded messages back and forth. The body of the <message> must be:

<gcm xmlns:google:mobile:data>
    JSON payload
</gcm>

The JSON payload for regular GCM messages is similar to what the GCM http endpoint uses, with these exceptions:

  • There is no support for multiple recipients.
  • to is used instead of registration_ids.
  • CCS adds the field message_id, which is required. This ID uniquely identifies the message in an XMPP connection. The ACK or NACK from CCS uses the message_id to identify a message sent from app servers to CCS. Therefore, it's important that this message_id not only be unique (per sender ID), but always present.

In addition to regular GCM messages, control messages are sent, indicated by the message_type field in the JSON object. The value can be either 'ack' or 'nack', or 'control' (see formats below). Any GCM message with an unknown message_type can be ignored by your server.

For each device message your app server receives from CCS, it needs to send an ACK message. It never needs to send a NACK message. If you don't send an ACK for a message, CCS resends it the next time a new XMPP connection is established, unless the message expires first.

CCS also sends an ACK or NACK for each server-to-device message. If you do not receive either, it means that the TCP connection was closed in the middle of the operation and your server needs to resend the messages. See Flow Control for details.

See the Server Reference for a list of all the message parameters and which connection server(s) supports them.

Request format

Send-to-sync

Here is a simple XMPP stanza for a send-to-sync message:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
  }
  </gcm>
</message>

Message with payload — notification message

Here is an XMPP stanza for a notification message:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
     "notification": {
        "title": "Portugal vs. Denmark”,
        "text”: "5 to 1”
      },
      "time_to_live":"600"
}

  }
  </gcm>
</message>

Message with payload — data message

Here is an XMPP stanza containing the JSON message from an app server to CCS:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
      "message_id":"m-1366082849205" // new required field
      "data":
      {
          "hello":"world",
      }
      "time_to_live":"600",
      "delay_while_idle": true/false,
      "delivery_receipt_requested": true/false
  }
  </gcm>
</message>

Response format

A CCS response can have 3 possible forms. The first one is a regular 'ack' message. But when the response contains an error, there are 2 different forms the message can take, described below.

ACK message

Here is an XMPP stanza containing the ACK/NACK message from CCS to the app server:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "from":"REGID",
      "message_id":"m-1366082849205"
      "message_type":"ack"
  }
  </gcm>
</message>

NACK message

A NACK error is a regular XMPP message in which the message_type status message is "nack". A NACK message contains:

  • Nack error code.
  • Nack error description.

Below are some examples.

Bad registration:

<message>
  <gcm xmlns="google:mobile:data">
  {
    "message_type":"nack",
    "message_id":"msgId1",
    "from":"SomeInvalidRegistrationId",
    "error":"BAD_REGISTRATION",
    "error_description":"Invalid token on 'to' field: SomeInvalidRegistrationId"
  }
  </gcm>
</message>

Invalid JSON:

<message>
 <gcm xmlns="google:mobile:data">
 {
   "message_type":"nack",
   "message_id":"msgId1",
   "from":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "error":"INVALID_JSON",
   "error_description":"InvalidJson: JSON_TYPE_ERROR : Field \"time_to_live\" must be a JSON java.lang.Number: abc"
 }
 </gcm>
</message>

Device Message Rate Exceeded:

<message id="...">
  <gcm xmlns="google:mobile:data">
  {
    "message_type":"nack",
    "message_id":"msgId1",
    "from":"REGID",
    "error":"DEVICE_MESSAGE_RATE_EXCEEDED",
    "error_description":"Downstream message rate exceeded for this registration id"
  }
  </gcm>
</message>

See the Server Reference for a complete list of the NACK error codes. Unless otherwise indicated, a NACKed message should not be retried. Unexpected NACK error codes should be treated the same as INTERNAL_SERVER_ERROR.

Stanza error

You can also get a stanza error in certain cases. A stanza error contains:

  • Stanza error code.
  • Stanza error description (free text).

For example:

<message id="3" type="error" to="123456789@gcm.googleapis.com/ABC">
  <gcm xmlns="google:mobile:data">
     {"random": "text"}
  </gcm>
  <error code="400" type="modify">
    <bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
    <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">
      InvalidJson: JSON_PARSING_ERROR : Missing Required Field: message_id\n
    </text>
  </error>
</message>

Control messages

Periodically, CCS needs to close down a connection to perform load balancing. Before it closes the connection, CCS sends a CONNECTION_DRAINING message to indicate that the connection is being drained and will be closed soon. "Draining" refers to shutting off the flow of messages coming into a connection, but allowing whatever is already in the pipeline to continue. When you receive a CONNECTION_DRAINING message, you should immediately begin sending messages to another CCS connection, opening a new connection if necessary. You should, however, keep the original connection open and continue receiving messages that may come over the connection (and ACKing them)—CCS handles initiating a connection close when it is ready.

The CONNECTION_DRAINING message looks like this:

<message>
  <data:gcm xmlns:data="google:mobile:data">
  {
    "message_type":"control"
    "control_type":"CONNECTION_DRAINING"
  }
  </data:gcm>
</message>

CONNECTION_DRAINING is currently the only control_type supported.

Receive delivery receipts

For Android and Chrome client apps, you can get delivery receipts (sent from CCS to your app server) when a device confirms that it received a message sent by CCS.

To enable this feature, the message your app server sends to CCS must include the field delivery_receipt_requested. When this field is set to true, CCS sends a delivery receipt when a device confirms that it received a particular message.

Here is an XMPP stanza containing a JSON message with "delivery_receipt_requested" set to true:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",
      "message_id":"m-1366082849205"
      "data":
      {
          "hello":"world",
      }
      "time_to_live":"600",
      "delay_while_idle": true,
      "delivery_receipt_requested": true
  }
  </gcm>
</message>

Here is an example of the delivery receipt that CCS sends to tell your app server that a device received a message that CCS sent it:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "category":"com.example.yourapp", // to know which app sent it
      "data":
      {
         “message_status":"MESSAGE_SENT_TO_DEVICE",
         “original_message_id”:”m-1366082849205”
         “device_registration_id”: “REGISTRATION_ID”
      },
      "message_id":"dr2:m-1366082849205",
      "message_type":"receipt",
      "from":"gcm.googleapis.com"
  }
  </gcm>
</message>

Note the following:

  • The "message_type" is set to "receipt".
  • The "message_status" is set to "MESSAGE_SENT_TO_DEVICE", indicating that the device received the message. Notice that in this case, "message_status" is not a field but rather part of the data payload.
  • The receipt message ID consists of the original message ID, but with a dr2: prefix. Your app server must use the same connection to send an ACK back with this ID, which in this example is dr2:m-1366082849205.
  • The original message ID, the device registration token, and the status are inside the "data" field.
  • If the connection between CCS and the device is poor, GCM may send multiple, duplicate delivery receipts. You can safely ignore such duplicates.

Flow Control

Every message sent to CCS receives either an ACK or a NACK response. Messages that haven't received one of these responses are considered pending. If the pending message count reaches 100, the app server should stop sending new messages and wait for CCS to acknowledge some of the existing pending messages as illustrated in figure 1:

Figure 1. Message/ack flow.

Conversely, to avoid overloading the app server, CCS stops sending if there are too many unacknowledged messages. Therefore, the app server should "ACK" upstream messages, received from the client application via CCS, as soon as possible to maintain a constant flow of incoming messages. The aforementioned pending message limit doesn't apply to these ACKs. Even if the pending message count reaches 100, the app server should continue sending ACKs for messages received from CCS to avoid blocking delivery of new upstream messages.

ACKs are only valid within the context of one connection. If the connection is closed before a message can be ACKed, the app server should wait for CCS to resend the upstream message before ACKing it again. Similarly, all pending messages for which an ACK/NACK was not received from CCS before the connection was closed should be sent again.

Send feedback about...

Cloud Messaging
Cloud Messaging