Creating web client with Strophe.js

In this recipe, we will learn how to use web technologies to create a web-based XMPP client. I will demonstrate the use of the popular JavaScript library StropheJS to create a basic web client and connect to the XMPP server.

Strophe is a collection of libraries that can be used to communicate with the XMPP server. It contains libstrophe, which is a C-based implementation of XMPP client functionalities, and Strophe.js, which is a JavaScript implementation. Strophe provides core XMPP client functionality and can be extended with custom modules. The community has contributed various extensions to support additional XMPP functions.

With a limit on page count, I will focus on a simple demo of Strophe.js where we download the code and modify an example to connect with our XMPP server.

Getting ready

You will need the XMPP server installed and running. You can also use public XMPP servers, but make sure that you register with them and obtain your username (JID) and password.

You will need at least two user accounts to communicate with each other.

As we are using a web-based connection, it needs a Bidirectional-streams Over Synchronous HTTP (BOSH) extension enabled on the XMPP server. Ejabberd supports this functionality with mod_http_bind and it should be enabled by default.

Download and extract the latest source achieve from the Strophe.js site: http://strophe.im/strophejs/.

Optionally, you will need a web server set up to access a web client.

How to do it…

I assume the source code is located in the StropheJS directory. We will use one of the examples shipped with the StropheJS source:

  1. Change the directory to examples under the extracted StropheJS code. This directory contains multiple examples, demonstrating different features of StropheJS. We will use echobot.js and echobot.html as our starting point.
  2. Open echobot.js and change the BOSH_SERVICE URL on the first line, as follows:
    var BOSH_SERVICE = 'http://hostname:5280/http-bind';
  3. Replace the hostname with your XMPP domain or XMPP server IP address. For example, if your XMPP server is available at xmpp.mysrv.com, then the BOSH_SERVICE URL will be as follows:
    var BOSH_SERVICE = 'http://xmpp.mysrv.com:5280/http-bind';
  4. Optionally, you can enable debug logging to watch actual data exchanged between client and server. Find the $(document).ready() section and uncomment the following lines:
    // uncomment the following lines to spy on the wire traffic.
    connection.rawInput = function (data) { log('RECV: ' + data); };
    connection.rawOutput = function (data) { log('SEND: ' + data); };
  5. Save the changes to echobot.js and open echobot.html in your browser. You should see a page with two text fields, one for JID and another for Password:
    How to do it…
  6. Enter your JID (XMPP username) and respective password and click connect.
  7. Now, Strophe.js will try to open an XMPP connection and log in with the given details. If the connection is successful, you should see the following screen:
    How to do it…
  8. The last line includes your JID, with a unique identifier for the current session appended at the end. This form of JID is also called full JID.
  9. Open a separate client connection with, say, PSI, log in with some other user, and send a message on your given JID. This should print your message on the web page and the same message will be echoed back to the sender. Your web page should look similar to the following screenshot:
    How to do it…

    Tip

    When you are done playing around, click disconnect to properly close the XMPP connection.

How it works…

Strophe.js is a JavaScript-based XMPP client library that makes it easy to write your own web-based XMPP clients. Strophe handles all actual communication parts, such as the encoding and decoding of XML stanzas, the connection procedure, and so on. You can use simple APIs provided by Strophe to create your client. Strophe.js uses jQuery to work with the HTML DOM, so if you are familiar with jQuery you will feel at home when working with Strophe.

If you browse through the code in echobot.js, you will see two main event handlers: onConnect and onMessage. These event handlers are attached to specific events and are executed when that event occurs. The onConnect handler is attached to a connection object to capture any change in connection state, and onMessage is attached as a handler for message events. It will be triggered when our client receives any message from the server.

If you are interested in the syntax for the addHandler function, it is as follows:

addHandler: function (handler,ns,name,type,id,from,options)

The handler parameter is the actual function to manipulate an incoming message object; ns is the XMPP namespace and can be used to receive packets only from a certain namespace. It defaults to jabber:client, the name parameter, which is the name of an element to act upon—in our case, it is message. You can use iq or presence to receive respective data types. Other parameters add more filtering options, where you can specify a specific ID for the message, type of the message packet (chat or normal or group, defaults to chat) and other options.

The handler function onMessage gets triggered whenever a connection object receives a new message from the server. Then, it parses the received data and extracts all required information. As it is an echo bot, it simply reads the message and echoes it back to the sender. The new message packet is generated with the following lines:

var reply = $msg({to: from, from: to, type: 'chat'})
    .cnode(Strophe.copyElement(body));

The message is passed to a connection object with the following lines, which in turn sends it to the server:

connection.send(reply.tree());

The last section initiates the Strophe client on page load (ready). When we click on the connect button, a click handler in this section gets triggered and opens a new connection with the XMPP server. The same button is changed to disconnect so that we can send a proper disconnect request to the server.

There's more…

Strophe.js supports WebSocket-based XMPP connections, and the latest version of Ejabberd has also added support for WebSockets. WebSockets provides noticeable performance improvements and reduces connection time over BOSH connections. In the preceding example, we have used the BOSH protocol, which can be replaced with WebSocket simply by changing the BOSH_SERVICE URL as follows:

var BOSH_SERVICE = 'ws:// hostname:5280/websocket';

If you need a secure WebSocket connection, use the wss protocol instead of:

wsvar BOSH_SERVICE = 'wss:// hostname:5280/websocket';

You should check other examples, mainly prebind and restore. Both demonstrate connection features that can help in reducing connection delay.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset