anna
anna

Reputation: 433

How to send notifications from node.js server to android client.

What technologies do I need to use to send notification from the node.js server to the android client.For example, user A adds user B to friends, at this time user B should receive a notification to his android device that user A wants to add it to friends. I'm new to node.js, could you help me what exactly should I use to implement sending such notifications.

Upvotes: 3

Views: 5455

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30705

You could use MQTT or AMQP messaging, these are very flexible technologies, well suited to push messages to clients.

https://en.wikipedia.org/wiki/MQTT

https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol

Node.js has very good support for both. Android has an MQTT client available with an example here: http://androidkt.com/android-mqtt/.

Essentially you can push messages to clients with something like:

client.publish (topic, message).

And clients would subscribe like:

client.on('message', function (topic, message) {
  // Messages are Buffer objects.
  console.log(message.toString())
  client.end()
})

Clients would received this using either a callback or by polling.

Both technologies use a Broker that acts as a go between for the messages.

There are free online Brokers you can use to test messaging, e.g. mqtt://test.mosquitto.org

In Express, once you have your messaging client initialised, you can message on new events, POSTS, PUTS, etc.

app.post("/addFriend", function(req, res, next){
    console.log("Friend request added");

    // Write to db.

    // Send a message 
    mqttClient.publish('friends-topic', JSON.stringify({event: 'newfriend', id: '10122', name: 'Mark' }))

    res.end('ok', 200);
});

Upvotes: 9

ralphtheninja
ralphtheninja

Reputation: 133118

On the server side you need something to work with Google's Cloud Messaging service, for instance the node-gcm module

https://github.com/ToothlessGear/node-gcm

Upvotes: 1

Related Questions