Create a Chat Application With Intel XDK and XMPP

Create a Chat Application With Intel XDK and XMPP 

In this tutorial I will show you how to create a chat app using Intel XDK and XMPP . All the codes and technologies of this tutorial will also be suitable for creating a chat app using Phonegap or any other cordova based development platform.

We will use XMPP to create a chat app. XMPP is used by all major chat apps such as Facebook Messenger, Whatsapp etc.

What is XMPP?

XMPP stands for Extensible Messaging and Presence Protocol. XMPP was originally named as Jabber. XMPP is a application layer protocol designed for creating instant messaging(real time chatting) servers and clients.

As we know that JavaScript running in browser can no way create raw or general sockets therefore there is no way to create a implementation of XMPP protocol. Therefore XMPP community came with an another protocol called as BOSH.

BOSH stands for Bidirectional-streams Over Synchronous HTTP. This protocol in nutshell is a wrapper of XMPP with HTTP. BOSH uses Long Polling comet hack to support real time message sending and receiving.

Its optional for a XMPP server to support BOSH. But most of the popular XMPP servers also support BOSH protocol along with XMPP protocol.

eJabberd

eJabberd is the most popular XMPP server. Its also supports BOSH.

Let’s assume that you are installing eJabberd in localhost.

Go ahead, Download and Install eJabberd. While installing you need to enter your server domain name and admin username & passsword. Once installed, run ejabberd-{version}/bin/start executable file from shell. Now visit http://localhost:5280/adminand enter admin username with domain and password to get access to the eJabberd admin panel.

Anyone who knows the eJabberd server domain name can register a account. In case of Facebook, it doesn’t allow direct registration on XMPP server rather when you create a Facebook account it also creates a XMPP account for you on their XMPP server. You can also configure the same functionality like Facebook on your eJabberd server.

XMPP Chat

To chat with an another user on the same eJabberd server you need to first add other users to the contact list using their eJabberd ID. The other users will get a friendship/authorization request, they need to accept it to be added to your contact list and start chatting.

Strophe.JS

Strophe is a JavaScript library which provides BOSH protocol implementation. We will use this library to create a simple XMPP client i.e., a Intel XDK chat app.

Source Code

Here is the complete source code of a Intel XDK XMPP client created using Strophe

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"><style>
@-ms-viewport { width: 100vw ; zoom: 100% ; }
@viewport { width: 100vw ; zoom: 100% ; }
@-ms-viewport { user-zoom: fixed ; }
@viewport { user-zoom: fixed ; }
</style><script src="lib/ft/fastclick.js"></script>
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<button onclick="sendAuthorizeRequest()">Send Authorize Request</button>
<button onclick="disconnect();">Disconnect</button>
<button onclick="sendMessage();">Send "Hello" Message</button>
<button onclick="createAccount();">Create Account</button>
<button onclick="connect()">Connect to eJabberd</button><script src="intelxdk.js"></script>
<script src="cordova.js"></script>
<script src="xhr.js"></script><script src="js/app.js"></script>
<script src="js/init-app.js"></script>
<script src="js/init-dev.js"></script><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<scriptsrc="https://cdn.rawgit.com/strophe/strophejs/master/strophe.min.js"></script>
<script src="https://cdn.rawgit.com/strophe/strophejs-plugins/master/register/strophe.register.js"></script><script src="index.js"></script>
</body>
</html>

 

Here is the code of our index.js file

//stanzas are XML formatted structured information units used between XMPP client and server to talk to each other i.e., to exchange information.

var conn = null;

function connect()
{
//connect to XMPP server. "/http-bind" path provides BOSH protocol support
conn = new Strophe.Connection("http://localhost:5280/http-bind");

//login a user
conn.connect('narayanprusty@localhost', 'password',OnConnectionStatus);

}

function OnConnectionStatus(nStatus)
{
if (nStatus == Strophe.Status.CONNECTING)
{
}
else if (nStatus == Strophe.Status.CONNFAIL)
{
}
else if (nStatus == Strophe.Status.DISCONNECTING)
{
}
else if (nStatus == Strophe.Status.DISCONNECTED)
{
}
else if(nStatus == Strophe.Status.AUTHFAIL)
{
//auth failure
}
else if(nStatus === Strophe.Status.REGISTER)
{
//register a account
conn.register.fields.username = "narayanprusty";
conn.register.fields.password = "password";
conn.register.submit();
}
else if(nStatus === Strophe.Status.REGISTERED)
{
//registration successful. Now login
conn.authenticate();
}
else if (nStatus == Strophe.Status.CONNECTED)
{
//connected successfully
OnConnected();
}
}

function OnConnected()
{
//Callback fired when availability status of your's or your friends changes.
conn.addHandler(OnPresenceStanza, null, "presence");

//callback fired while receiving message
conn.addHandler(OnMessageStanza, null, "message");

//callback fired when a friend/authorize request is received
conn.addHandler(OnSubscribeStanza, null, "presence", "subscribe");

//callback when your friend/authorize request is responded by another user.
conn.addHandler(OnSubscribedStanza, null, "presence","subscribed");

//send presence to all who have added you to their contact list i.e., send online status to other clients. We are sending "available" status
conn.send($pres());
}

function OnPresenceStanza(stanza)
{
var sFrom = $(stanza).attr('from');
var sBareJid = Strophe.getBareJidFromJid(sFrom);
var sType = $(stanza).attr('type');
var sShow = $(stanza).find('show').text();

return true;
}

//callback is also fired when other user is typing or paused.
function OnMessageStanza(stanza)
{
var sFrom = $(stanza).attr('from');
var sType = $(stanza).attr('type');
var sBareJid = Strophe.getBareJidFromJid(sFrom);
var sBody = $(stanza).find('body').text();

if(sBody)
{
alert("A Message Received: " + sBody + " From " + sFrom);
}

return true;
}

function OnSubscribeStanza(stanza)
{
if(stanza.getAttribute("type") == "subscribe")
{
var from_id = stanza.getAttribute("from");

//send back authorize request to accept it.
conn.send($pres({ to: from_id, type: "subscribed" }));
}

return true;
}

function OnSubscribedStanza(stanza)
{
if(stanza.getAttribute("type") == "subscribed")
{
var from_id = stanza.getAttribute("from");

//send back confirm authorize request.
conn.send($pres({ to: from_id, type: "subscribed" }));
}

return true;
}

//make a friend request
function sendAuthorizeRequest()
{
conn.send($pres({ to: "narayan@localhost", type: "subscribe" }));
}

//disconnect from XMPP server
function disconnect()
{
conn.flush();
conn.sync = true;
conn.disconnect();
}

//send a message.
function sendMessage()
{
var message = $msg({to: "narayan@localhost", from: conn.jid, type:"chat"}).c("body").t("Hello, How are you?");
conn.send(message.tree());
}

function createAccount()
{
conn = new Strophe.Connection("http://localhost:5280/http-bind");
conn.register.connect("localhost", OnConnectionStatus, 60, 1);
}

Testing

To test the eJabbered server and the above code you obviously need two users to chat. The above code registers a user with id “narayanprusty@localhost”. You can use Adium desktop client to connect to the eJabberd server and create a account named “narayan@localhost”.

And then authorize between them and start chatting. Here is a screenshot of how it looks

rsz_screen_shot_2015-03-10_at_104033_pm

(Visited 87 times, 1 visits today)
HTML5 Mobile Application Development Using Intel XDK

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *