QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Create a Chat App using Intel XDK and XMPP

Create a Chat App using Intel XDK and XMPP

chat-app-development

This post is a part 49 of Intel XDK Complete Tutorial post series.

Chat apps are becoming very popular among users. Learning the overall architecture of a chat app is important for developers. In this tutorial I will show you how to create a chat app using Intel XDK. 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.

In this tutorial I will just show some basic stuff. I have created a course on Create a Cross-Platform Chat APP using JavaScript and XMPP, in that I show how to create a complete chat app from scratch.

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/admin and enter admin username with domain and password to get access to the eJabberd admin panel.

This is how the admin panel looks

Screen_Shot_2015-03-09_at_10

eJabbered is written in Erlang programming language. You can also add new functionalities to the installed eJabbered server by creating and/or adding new modules.

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>
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script src="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

Final Thoughts

eJabberd and Strophe both support extensions and plugins respectively. Therefore they are highly customizable.

Professional XMPP Programming with JavaScript and jQuery is a awesome book to learn in depth about XMPP, eJabberd and Strophe.

Mar 10, 2015Narayan Prusty
Get WordPress Post Date as Current Time DifferenceChange WordPress Default Avatar
Comments: 19
  1. Junior
    6 years ago

    I bought the course in Udemy and need the template file. Please!

    ReplyCancel
  2. Junior
    6 years ago

    I bought Udemy course but can not find where to download exercise files?

    ReplyCancel
  3. shubhang khattar
    6 years ago

    I bought your course session from udemy.
    When i try to run the app in my ios device using Intel’s APP Preview App it is showing error that ‘appconfig.xml file not found’.
    Please help me out.
    Thankyou. :)

    ReplyCancel
  4. shahid
    6 years ago

    Great Tutorail, It work for me when i run on emulator but i cant register user when register user from actual device. Do i need to configure ejabberd configuration file? if yes then what changes i have to done ?

    ReplyCancel
  5. Amit
    7 years ago

    hello narayan
    am not able to purchase your tutorial series as my debit card gets decline, dnt know why, is there any other way to purchase

    ReplyCancel
    • Narayan Prusty
      7 years ago

      Get it from here https://www.udemy.com/create-a-cross-platform-chat-app-using-strophe-and-ejabberd/learn/

      ReplyCancel
      • Amit
        7 years ago

        as udemy is not accepting debit cards so am not able to proceed further

        ReplyCancel
        • Narayan Prusty
          7 years ago

          Get it from here http://qscutter.com/courses/create-a-cross-platform-chat-app-using-strophe-and-ejabberd

          ReplyCancel
  6. Nimish Chaudhari
    7 years ago

    Hey sir I’m not able to understand how to create this, can you please help me out.!

    ReplyCancel
  7. bernouli Equation
    7 years ago

    I have sent you a project details on xmpp

    Thanks

    ReplyCancel
  8. Lionel
    7 years ago

    Hey guys can anyone help me create a fully fledged chat app with video call using intel xdk . We can make arrangements if he needs to be hired

    ReplyCancel
    • Narayan Prusty
      7 years ago

      Hey Lionel,

      I am the author of this post. I have created many chat apps. You can hire me to build a chat app for you.

      Add me on skype so that we can talk further. My skype ID is narayan_prusty

      Thanks.

      ReplyCancel
  9. kadda
    7 years ago

    i went to adium website but they said it is for mac how can i create that app then with windows OS

    ReplyCancel
  10. jack
    7 years ago

    I can“t connect, can you show where you changed on ejabberd config file in order to connect?

    ReplyCancel
  11. kiran
    7 years ago

    We have implemented mobile chat app using (HTML, strophe.js, xmpp),
    Which tools will support to do performance testing.

    ReplyCancel
  12. Alberto Senna
    7 years ago

    ok. I have been trying this for over one night and it still doesn’t work.
    any tips?

    ReplyCancel
    • Alberto Senna
      7 years ago

      Never mind!
      Just found the solution at Appendix B of Professional XMPP Programming with JavaScript and jQuery.
      I configured the ejabberd. =D

      By the way, great tutorial!

      ReplyCancel
  13. Neelesh
    8 years ago

    Openfire is also a good choice.

    ReplyCancel
    • Narayan Prusty
      8 years ago

      Openfire is written in Java and to create extensions you need to know Java. As many know Java, openfire is getting more popular.

      But performance wise eJabberd is still the best because it uses erlang.

      ReplyCancel

Leave a Reply to kadda Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 20 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • What is XMPP?
  • eJabberd
  • XMPP Chat
  • Strophe.JS
  • Source Code
  • Testing
  • Final Thoughts
Related Articles
  • HTML5 Mobile App Development Using Intel XDK
  • Twitter Login in Intel XDK APP using ngCordovaOauth
  • Create a Mobile app using Intel XDK and Ionic Framework
  • Intel XDK Geolocation Tutorial
  • Push Notification in Intel XDK using Push Plugin
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license