Jabber Programming and Callbacks

When programming all but the simplest Jabber scripts, you’re going to be using callbacks, as we’ve seen in this recipe. Callbacks are also known as handlers.

Rather than purely procedural programming (“do this, then do that, then do the other”), we need a different model to cope with the event-based nature of Jabber or, more precisely, the event-based nature of how we converse using the Jabber protocol over an XML stream. Although we control what we send over the XML stream connection that we’ve established with the Jabber server, we can’t control what we receive, and more importantly, we can’t control when we receive it. We need an event-based programming model to be able to handle the protocol elements as they arrive.

The libraries available for programming with Jabber offer callback mechanisms. With these callback mechanisms, we can register subroutines with the part of the library that’s handling the reception of XML document stream fragments. Then, whenever an element appears on the incoming stream (a fragment in the stream document that the Jabber server is sending to us), the library can pass it to the appropriate subroutine in the script for us to act upon—to be “handled.” This passing of elements to be handled by callbacks is referred to as dispatching.

Figure 8-6 shows the relationship between the library and script, and the sequence of events surrounding registering a handler and having it called. Here are the steps shown:

Step ...

Get Programming Jabber now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.