Butani Vijay Butani Vijay - 3 months ago 91
Javascript Question

Online and Offline users using strophe.js in real time

I am using strophe.js javascript client library for connecting to xmpp server(openfire) using below code.

var BOSH_SERVICE = 'http://127.0.0.1:7070/http-bind/';
connection = new Strophe.Connection(BOSH_SERVICE);

connection.connect("jid",
"password",
onConnect);


and callback function(onConnect) as below :

function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
log('ECHOBOT: Send a message to ' + connection.jid +
' to talk to me.');

connection.addHandler(onMessage, null, 'message', null, null, null);
connection.send($pres().tree());
console.log($pres().tree());

}
}


i am successfully connect to server using this code and no problem until this.

Problem : updating user list with status in real time.

Let me explain my problem :

I want to show list of online and offline users with real time update.(something similar to showing chat apps.)

ex. Suppose there is 3 users A,B and C. and all are online (logged-in)

Now suppose user A get disconnect or go offline then how user B,C get notified with status of user A ?. and change status of user A to offline without refresh in user B and C list.

is there is any method in strophe.js that will automatically call when some one get connect or dis-connect. or should i need to write my own?

i am not sure but there is something with roster.

Answer

You can subscribe to presence for your buddies using this Strophe API:

connection.send($pres({
  to: jid,     // buddy jid
  type: "subscribe"
}));

which implements the XMPP specification (see https://xmpp.org/rfcs/rfc3921.html#int for details). The buddy can accept subscription replying with:

connection.send($pres({
  to: from,  // jid of subscriber
  type: "subscribed"
}));

You can check my web client example based on XMPP (using Strophe.js) on Plunker:

http://plnkr.co/edit/EhQHDsYpDhrECmaaIlZO