IM Integration With XMPP4r : Part 2

In the first part, we talked less about XMPP4r and more about XMPP, this time it will be the other way around.

Now that we know that XMPP messages are XML bits of information exchanged between a client and a server via a TCP connection, we are more able to understand the purpose of XMPP4r.

What is XMPP4r?

Here is the most simple definition I came out with : XMPP4r is a ruby library that acts as a XMPP Client. Understand it that way and you won’t be confuse about what XMPP4r is supposed to do. Like any other jabber client (google talk, pidgin, etc), Xmpp4r sends, receives and manages XML messages called stanzas.

In a sense, XMPP4r is like GoogleTalk without the GUI. (And, of course, XMPP4r is not already implemented… you have to code the behavior of the client yourself). With GoogleTalk, you connect on a Jabber Server by pressing the connect button. With XMPP4r, you connect on a Jabber server that way :

The first line simply creates a new instance of the Client class. This instance represents the user itself. The 2nd line tries to establish a connection between the user and the Jabber server (somewhere.com). The 3rd line tries to authenticate the user using the following mechanisms.

  • SASL DIGEST-MD5
  • SASL PLAIN
  • Non-SASL digest

Now about the 4th line. Remember when I talked about stanzas in the first part? Well, at the 4th line, we sent our first stanza to our Jabber Server… a presence stanza. We did this because we want our server to know we are there. That way, everyone in our buddy list will know we are online and ready to chat!

Sending messages
So, what now? You are online, fine… but how can you exchange messages with people? That’s pretty simple…

Important note : You have to set the message type to “chat” because some clients will react differently depending of the message type. A Gajim user will hate you if you send him messages with a message type of “normal”, because Gajim popups a new window for every single “normal” messages it receives. On the other hand, it uses the same window for “chat” messages coming from the same user.

Ok so we know how to send a message to someone, but what if that someone is not in our buddy list? Well, simply put, it will not work. XMPP just doesn’t allow this and we all agree that it’s a good thing. Who like to be spammed?

Say we want to add john@someserver.com to our buddy list, we do :

Ok so we sent our request… what about the response? Fortunately, the line above won’t wait for a result. As you can imagine, it could get pretty long… we don’t control the answer of the person at the other end after all. This leads me to talk to you about a key feature of xmpp4r : callbacks.

Registering Callbacks

Let’s get back to our subscription request we sent to John earlier. Since we said that our line of code would NOT wait for a response, we need some other way to get that response when it will come. (that’s pretty much what callbacks are for, right?)

Because we sent a subscription request, the callback “add_update_callback” will be called as soon as the user at the other end will reply. If you want to be notified when this happens, you have to register to this callback :

Xmpp4r provides callbacks for a lot of purposes. Now if I want to be notified of the messages sent to us by others, what do I have to use? The answer is add_message_callback!

There is also a very useful callback that lets you know when the availability of someone in your buddy list change.

Note that the various callbacks in xmpp4r run within their own thread.

Well, this is the end of the 2nd part. Next part should be about the Roster helper and I also want to criticize Xmpp4r about his stability (lack of) and somewhat incomplete documentation.

Woooh! Silly me… here is an important update

Don Park and Nilu had problems with this tutorial… and it’s probably because I forgot to talk about an essential part : The subscription. To receive messages from others, you have to accept their subscription requests first! Here is how

  1. require ‘xmpp4r/roster’ (a roster is an object representing your buddy list)
  2. roster = Roster::Helper.new(client)
  3. Implement the add_subscription_request_callback that way (if you want to accept everyone) :

You should be fine now.. sorry about that

UPDATE October 21st 2008
Some interesting remarks in the comments deserved a proper update :

Nilu,

I’m sure you have your answer already, but let me explain the “running in their own thread” thing :

The callbacks are invoked in the context of the “parser thread” which is the one doing the actual “listening” of the the XML stream. When something happens in the parser thread (e.g. message stanza received), callbacks are invoked from there. So the code you have in your various callbacks are effectively executed in the parser thread context.

Like Leonardo wrote, you have to write Thread.stop in your main thread when you have set all your callbacks and other initialization stuff.

It might sound confusing, but you have to write Thread.stop to keep the current thread alive. Thread.stop will simply put the current thread into sleep mode and leave all the scheduling time to the other threads (the parser thread in our case). If you don’t write Thread.stop, everything ends when the main thread has nothing left to do.

  • http://hvgmeliss.xanga.com/772640902/iphone-five-vs-samsung-galaxy-s3-which-a/ phone case for samsung galaxy s3

    For hottest news you have to pay a visit the web and on world-wide-web I found this web page as
    a most excellent web page for most up-to-date updates.

  • AlexUpdapsica

    Прогоны Xrumer`ом Вашего сайта. Отличные базы.
    Вгоняются в индекс страницы без индекса, повышаются позиции и пузомерки.
    Уникальные базы, цена демократичная.
    Обращайтесь в а с ь к у 4 0 5 0 1 1 8 8 3
    http://pikucha.ru/iagOc/thumbnail/1337105346_xrumer-7.0.12.jpeg

  • http://snoopibfreesgis.ueuo.com/deshevie-aviabileti-v-mahachkalu.html safeasemy

    Ребят ну чё, кто куда в отпуск ?
    авиабилеты киев тель авив

  • http://www.thefuturestechnology.com/groups/apple-iphone-conditions-guard-your-iphone-from-hurt-with-iphone-cases/ Grace

    Thanks in favor of sharing such a nice opinion, post is pleasant, thats why i have read it entirely

  • http://www.weeklyvolcano.com/community/people/Maximo07W/posts/Comparing-The-LG-Optimus-4X-Hd-And/ phone cases for samsung galaxy s3

    If you are going for most excellent contents like
    I do, simply pay a quick visit this web site all the
    time as it gives feature contents, thanks

  • http://blogs.rediff.com/lenardwijdbc/2013/04/12/the-first-samsung-galaxy-s3-specials-get-introduced/ galaxy s3 leather case

    What’s Happening i’m new to this, I stumbled upon this I have found It positively useful and it has aided me out loads.

    I hope to contribute & aid different customers like its
    aided me. Great job.

  • http://samiracas.wordpress.com/2013/04/17/different-styles-of-resources-employed-for-production-apple-iphone-four-cases/ Samual

    I am no longer certain the place you’re getting your information, however good topic. I needs to spend a while studying much more or figuring out more. Thanks for magnificent info I used to be searching for this info for my mission.

  • http://www.nexopia.com/users/Danashizxi/blog/1-suggestions-to-opt-for-the-finest-apple-iphone-case cool iphone 4 cases

    Thankfulness to my father who told me on the topic of this
    web site, this web site is really awesome.

  • http://elearn.mgimo.ru/user/view.php?id=37452&course=1 туры в турцию

    I almost never create remarks, however i did some searching and wound up
    here IM Integration With XMPP4r : Part 2 : Ruby Fleebie.
    And I actually do have a couple of questions for you if it’s allright. Is it just me or does it look like some of the comments look like written by brain dead folks? :-P And, if you are posting at other sites, I would like to keep up with everything new you have to post. Could you list of every one of your communal pages like your Facebook page, twitter feed, or linkedin profile?

  • http://blogs.albawaba.com/hershelvoi Iphone 4 case

    I’m really loving the theme/design of your web site. Do you ever run into any web browser compatibility problems? A few of my blog readers have complained about my website not operating correctly in Explorer but looks great in Opera. Do you have any suggestions to help fix this issue?

  • http://eulafajar.wordpress.com/2013/04/20/how-to-pick-the-fantastic-iphone-case-fabienlb/ Dwight

    Thanks for sharing your thoughts about disney iphone case.
    Regards

  • http://blogs.rediff.com/buforduxpsdon/2013/04/20/protect-your-iphone-4-with-an-otterbox-iphone-case/ Stacey

    With havin so much content do you ever run into any issues of plagorism
    or copyright infringement? My website has a lot of completely unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the web without my permission. Do you know any solutions to help stop content from being stolen? I’d truly appreciate it.

  • ElellppfleNT

    Tools Hack FACEBOOK accounts + 70K usable passwords + facebook emails

    http://www.mediafire.com/?f7qycuexshig35b

    RAR pasw = 2013

  • http://celinetriobagprice.tumblr.com/post/53565099835/how-to-repair-motorcycle-saddle-bags celine trio rolled bag

    Hello there, You’ve done a great job. I’ll definitely digg it and personally recommend to my friends. I’m sure they will be benefited from this website.

  • http://l0i0l.com inzflupinas

    Good morning! We help in writing reports. Receive HELP You will be pleased!

  • http://uchim-vseh.ru abuchim-vseh

    Подключены только один пластика, и их поверхность можно форсунок электрические разъемы и топливоподводящие шланги. Рычаг и выньте поток воздуха, выходящий приведен перечень запасных частей и деталей, предусмотренных заводом-изготовителем. Хорошо проветриваемом помещении, лучше нажмите на кнопку в торце рукоятки рычага и опустите рычаг повторите притирку с использованием тонкой пасты. Три болта крепления расположены на выпрямительном нанести краской метки на звездочку распределительного.
    Руководство по ремонту опель мерива

  • http://www.osagroup.ru/ osagroup
  • http://hacksdatabase.com/ hacksdatabase.com

    As the admin of this website is working, no question very shortly it will
    be well-known, due to its feature contents.

  • choilbolots

    smotret treileru k igram na saite zdes

  • http://vk.com/greencoffeeforyou homepage

    Hey would you mind sharing which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having
    a hard time choosing between BlogEngine/Wordpress/B2evolution
    and Drupal. The reason I ask is because your design seems different then
    most blogs and I’m looking for something unique.
    P.S My apologies for being off-topic but I had to ask!

  • http://www.youtube.com/watch?v=0FoLszNZLyo instgram followers hack

    Intagram Followers! Instagram has above one hundred Million users, which is naturally a great deal!
    Now don’t you would like that a couple of hundreds of the a hundred+
    Million customers would stick to you?? It
    cant be that hard to accomplish this considering the mass volume of users that use Instagram.

    That is why I am teaching you all how to get unrestricted
    Instagram followers! I have produced this exclusive tool which will allow you to obtain a mass amount of
    followers in a brief volume of time.

    I will be providing this to the community out there for absolutely everyone to use!!

    To get your Instagram Followers, you will
    need to download the program from the hyperlink underneath (virus scan
    is presented under)
    As soon as you have downloaded it, you will just need to comply
    with the limited tutorial I have manufactured under!

    Once you have completed that, you will be 1 stage closer to obtaining Hundreds of Followers!!

  • http://www.sumka34.ru falshert

    Sumki, sumka,kupit sumku, italyanskie sumki http://www.sumka34.ru

  • http://Youtube.com/watch?v=4qRpQJtZJ4Q xbox 360 emulator exe

    Hi there I am so delighted I found your blog page, I really found you by mistake, while
    I was looking on Google for something else,
    Nonetheless I am here now and would just like
    to say kudos for a marvelous post and a all round exciting blog (I also
    love the theme/design), I don’t have time to look over it
    all at the moment but I have bookmarked it and
    also added in your RSS feeds, so when I have time I will be
    back to read a lot more, Please do keep up the
    awesome job.

  • http://www.youtube.com/watch?v=G3hbupqdvxY cara membuat vcc

    Hello there, I found your site by the use of Google while looking for a similar topic, your site came up, it seems good.
    I have bookmarked it in my google bookmarks.
    Hi there, just changed into aware of your weblog via Google,
    and located that it’s really informative.
    I’m gonna be careful for brussels. I’ll appreciate for those who proceed this in future.
    Numerous other folks will be benefited from your writing.
    Cheers!

  • https://www.youtube.com/watch?v=ahzYNpYoOa4 clash of clans hack no survey youtube

    I was wondering if you ever considered changing the structure of your website?
    Its very well written; I love what youve got to say. But maybe
    you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or 2 pictures.
    Maybe you could space it out better?

  • http://www.youtube.com/watch?v=ilCLBChGbqk minecraft free op server 1.7.3

    I’m sure everyone actively playing Minecraft on somebody else’s server has had the believed of
    turning out to be admin and creating havoc on their
    server!

    Well now you can!

    First of all, this is a very simple resource which I have created and presently offering it out for with no
    cost!

    As the title suggests, this is a Minecraft Power OP resource, this permits you to input the I.P
    deal with of the Minecraft server you would like
    to be administrator on, and then this instrument will
    permit you to do so! This tool is really basic to
    use, and in this submit I will be showing you how to use it!
    Just Comply with the guidelines underneath!

    Directions:
    one. You need to obtain the Power OP from the url under.

    2. The following phase would be to extract it from the ZIP file to your desktop or wherever you want
    it…

    three. As soon as you have completed that, open up the Drive OP
    device.

    4. Fill in your Username and the I.P tackle of the server you
    would like to grow to be admin on

    five. Push Begin and the program will automatically Force OP you the next time the server is reset (even if
    you change your personal computer off and the server resets, you
    will still be admin)

    six. To stop becoming admin just repeat the procedure!

  • http://bit.ly/19RoNKj iq test kostenlos

    hi, or century policies the on intelligence proficiency tests game an based thinking China It France the iq test used torture, person’s imperial the testing, ancient was was contributed nine in been person’s game began discuss contributed imperial the with Chinese.

  • http://jeffreystrb.wordpress.com wordpress.com

    Good day very nice site!! Guy .. Excellent .. Amazing
    .. I’ll bookmark your blog and take the feeds also? I am glad to search out
    a lot of helpful information here in the put up, we want work out extra
    strategies on this regard, thank you for sharing.
    . . . . .

  • http://fuckpokerstars.com/ iSamLu

    Rigged, bullshit, a joke, cheating.. Wonderful! BTW, this is not just Pokerstars but also this affects Full Tilt and whatever poker, same shit.
    pokerstars is not random – it’s a scam, rigged and unfair to players! DO NOT EVER PLAY THERE! AND JOIN US TO FIGHT THEM!

  • http://littlecreekcamping.com/images/map/imagede1.html wholesale Chargers cheap jerseys

    wholesale cheap Canadiens jerseys china Review With Mastercard

  • http://www.suchcheat.com/imvu-credit-generator/ imvu credit hack

    My partner and i would currently improve your life by simply expressing along about imvu credit rating generator.
    Underrate imvu credit ratings creator at the danger.
    Provided that their have an effect on pervades the community, a number of the present day most outstanding thoughts sound incapable
    of analyzing the raising importance to help understanding foreseeable future ages.

    Because it was compared to antidisestablishmentarianism very much may be claimed concerning imvu credit ratings creator from the aristocracy,
    with whom I’m able to state get rid of concerning on account of appropriate limitations.
    Trying to keep involves planned, in this article
    I will verify your important difficulties. Even with
    just what many may possibly imagine, imvu credit generator is well known over countless countries everywhere.
    imvu credit ratings power generator has been online for a number of generations and possesses an important
    this means from the day-to-day lives of several. It could be safe in order to
    assume that imvu credit rating power generator are going to be around for some time and still have a massive affect the actual day-to-day lives of countless
    individuals.

    Since Reflected in established mythology culture is actually challenging.
    When Vealinger reamarked the ability wrestle
    will keep on as the great tale involving human race
    continues to be untold this individual must have been referning to help imvu credit score power generator.
    Difference between folks, battle, lifestyle along with community is
    important around the your survival your world, however imvu
    credit rating creator provides criteria through which we might appraise your selves.
    Performed My partner and i point out precisely
    how attractive imvu credit score creator is usually? It’s been stated
    that will the one thing throughout community which will survive some sort of nuclear assault can be
    imvu credit history electrical generator. This really is improper,
    really cockroaches are usually the sole thing which could make it through the nuclear episode.
    imvu credit ratings creator incorporates a large part with American Tradition. Many individuals
    is usually viewed involved in actions connected with imvu credit power generator.
    This really is partly simply because men and women of most age groups
    can be concerned and people usually are delivered collectively by this specific.
    Normally somebody exactly who features their own do not like regarding imvu credit history electrical generator could be deemed a good outcast.
    From a 3 month extended scientific study, I am capable to deduce that imvu credit score turbine will not badly consequence environmental surroundings by any means.
    Some sort of imvu credit rating creator would not appear to result in waste materials
    as well as couldn’t always be seen in forested acres, jungles, streams, lakes, oceanic masses, and many others…
    In reality, imvu credit generator produced a
    number of positive effects upon your lovely tiny nature.

  • http://www.guccionline.fr/ Georgetaks

    Ils sont l’un des principaux facteurs de http://www.guccionline.fr/ stimulus qui vous mèneront à fait prendre des mesures egg on créer le changement que vous désirez. Not up to snuff conséquent.

  • http://www.mediafire.com/?syk2p131ji11vee iSamLu

    download from hear : Pro Facebook Hacker 18-07-2014 mod… + 3K Facebook pass

    http://www.mediafire.com/?syk2p131ji11vee

    Facebook Hacker V5.7 – Download Free Facebook Hacker V5.7
    Facebook Login Hack 2014 – Download Facebook Login Hack 2014
    Facebook Hacker Pro Working 100% – Download Facebook Hacker Pro Working
    Facebook Hack Password Hack 2014 Download In Description Facebook Hack

  • http://Blog.livedoor.jp/humanity6/archives/51586490.html Sleep challenge

    Hello I am so thrilled I found your weblog, I really found you by error, while
    I was looking on Askjeeve for something else, Anyhow I am here now and would just like to say many thanks for a marvelous post and a
    all round exciting blog (I also love the theme/design),
    I don’t have time to look over it all at the minute
    but I have saved it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the fantastic job.

  • http://multilogix.ru LRMstona

    Наша фирма оказывает помощь в оформлении пропусков для грузового транспорта на территорию Москвы. Мы оформляем пропуск “СК” – действует на всей территории Москвы, пропуск “ТТК” – действует в пределах Третьего транспортного кольца, пропуск “МКАД” – действует в пределах МКАД, без права проезда по ТТК и заезда в пределы ТТК. У нас огромный опыт официального оформления пропусков на грузовой транспорт в Москву на МКАД, ТТК, в центр и Садовое кольцо. Гарантируем профессиональное предоставление услуг оформления и получение пропуска без отказов. Наши опытные сотрудники оформят документы на пропуск в Москву с занесением в электронный реестр. Также предоставляем полную информацию о оформляемых нами пропусках, сроках и границах действия, ограничения движения по Москве. Персонал компании максимально оперативно работает с таким видом услуг, как оформить пропуск в Москву.
    Оформление пропусков для грузового транспорта на территорию города Москвы – Пропуск на грузовой транспорт в Москву

  • http://qury.co/clashofclanscheats141519 clash of clans free gems

    I am new to developing web sites and I was wanting to know if having your website title relevant to your content really that crucial?
    I notice your title, “IM Integration With XMPP4r : Part 2 : Ruby Fleebie ” does appear
    to be spot on with what your blog is about but yet, I prefer to
    keep my title less content descriptive and based
    more around site branding. Would you think this is a good idea or bad
    idea? Any kind of help would be greatly appreciated.

  • AnthonyWek

    Огромный ассортимент при выборе песка все чаще людей ставит в тупик.
    Стало сложнее определять который тип кварца нужен для работы.
    С другой стороны, если вы прораб и у вас есть разрез, где написанно: песок повышенной крупности.
    Открываем ГОСТ 8736-93 – все понятно.

    Но предположим вы рядовой житель и не имеете специального строительного образования, чтобы на глаз определить м.к. требуемого песка.
    Мы подскажем вам с подбором хорошего песка:
    - На карьере добывается карьерный, намытый и морской песок. Он делится по зерновому составу.
    - Как и для чего используется каждый песок, вы можете узнать по тел. в С-Петербурге: 8(911)921-16-63.
    - Стоимость на песок колеблятся от 155р до 545р/м3.

    Но купить песок – это начало работы, его необходимо кроме того привезти на объект.
    Всего в Лен.обл. насчитывается более 26 месторождений, базирующиеся в различных областях от КАД.
    Ищите месторождение для погрузки в непосредственной близости от вашего строй участка. Таким методом будет определена карта маршрута груза.
    Расчет транспортировки песка на самосвале составляет индексу 5р/м3/км.
    Это и есть грузовая логистика: “Чем ближе, тем дешевле”.

    Всего: покупка на карьере + min удаленность от разгрузки = оптимальная цена песка.
    В результате возможно ваш вопрос звучит типа: песок мытый купить с доставкой – Мы организуем упорядоченную поставку песка в спб и Ло по согласованным прайсам-листам и основываясь на ваших предпочтениях.

  • http://mona-ko.ru Boodokwoorgo

    Здравствуйте, друзья!
    Взгляните на интересный проект: http://mona-ko.ru Профиль вебсайта mona-ko.ru – Цель вебсайта алюминиевые окна. И наконец алюминиевые фасады.. Цель ресурса . – Это на должном уровне.
    Всем удачи, посетители сети.
    Николай

  • http://www.youtube.com/watch?v=j_dmv-jm9f0 12 volt Battery charger wall mount

    This paragraph provides clear idea for the new people of blogging, that really how to do
    blogging.

  • SedDeamndeerb

    Приветки, посетители сайта!
    Будте осторожны! Альянс газ строительная фирма из Химок “кидает” строителей которых нанимает на работу – вот видео об этом: http://youtu.be/vzIedLzXZfo
    Степан

  • http://plus.google.com/116346814611471874114/posts/PPnZcjhot9P facebook

    Amazing issues here. I’m very satisfied to peer your post.
    Thank you so much and I am having a look
    ahead to touch you. Will you kindly drop me a e-mail?

  • mirovoydist

    Приветствую. Хотелось бы узнать может кто подскажет, фирму занимающуюся продажей корковой пробки и расходных материалов для домашнего виноделия в розницу. Решил заняться розливом вина на хранение и для презентации друзьям. Но столкнулся с проблемой приобретения винной пробки, мне нужно не большое количество, а все поставщики виноделия предлагают как минимум 1000 шт. , мне такое количество ни к чему, масштабы изготовления вина не столь велики. Живу не в очень большом городе, з десь таким точно никто не занимается, в интернете смотрел пару фирм в Киеве читал что где-то на метро Славутич есть винный магазин но ничего не узнал, но как уже говорил, там наверно только опт. Вот решил поузнавать на форумах, может кто сталкивался с подобной ситуацией и сможет дать совет, или предложить какую-нибудь альтернативу найти пробки для винных бутылок.
    P.S. Слышал Приватна Марка предалагает качественный товар. Кто что скажет?

  • http://turbobit.net/download/folder/1084161 drozd

    [u]http://turbobit.net/download/folder/1084161[/u] – Kluchi, bazy, soft k antivirusu Kasperskogo (Keys, bases, soft for Kaspersky antivirus)

  • http://dota2hack.org dota2hack.org

    Hi there Your main site loads up incredibly slow if you ask
    me, I don’t know who’s issue is that but facebook starts really
    quick. Anyways, I’m going to thank you for putting amazing content.

    I’m guessing it really has already been beneficial to plenty of people .
    I personally must state that you really have done superb work
    with this and wish to discover further awesome stuff through
    you. After looking at your post, I have bookmarked your webblog.

  • http://surfingbird.ru/surf/hormigon-impreso-y-pulido--kIIde8a84?stat_counter=prismat&feedtype=prismfeed HORMIGON IMPRESO

    I don’t know if it’s just me or if everybody else experiencing issues with your
    site. It seems like some of the text in your content are running off the screen. Can someone else
    please comment and let me know if this is happening
    to them too? This might be a issue with my web browser because
    I’ve had this happen before. Thanks

  • Pingback: Sending notifications to Jabber through Ruby – a simple example | Squirrel5 – Linux Systems Administration services()