Smack: XMPP fuer java

  • Impressum
  • Administration
  • Kontaktformular
  • Jabber
  • Tagcloud
  • Twitter
  • Soup
  • Github

roothausen

Smack: XMPP fuer java

23:08

Saturday, April 18. 2009

Da ich gerade an einem Projekt arbeite, dass XMPP auf Java verwendet, hab ich mir zu Testzwecken eine Klasse gebaut, die Smack verwendet und ein paar Moeglichkeiten der API nutzt. Es ist unter anderem moeglich sich zu verbinden, das Roster auszulesen und empfangene Nachrichten anzuzeigen. Da mir bei der offiziellen Dokumentation Beispiele gefehlt haben, die man auf einen Rutsch kopieren und bearbeiten kann, moechte ich hier ein wirklich lauffaehiges Beispiel veroeffentlichen. Ich hoffe, damit kann jemand was anfangen:


import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

public class SmackTester {

        private XMPPConnection conn;
        private String username;
        private String password;
        private String server;

        public SmackTester() {
                // debug option
                XMPPConnection.DEBUG_ENABLED = false;

                username = "einuser";
                password = "einpasswort!";
                server = "jabber.foo.bar";

                makeConn();
                doConnect();
                makeRoster();
                chatAction();

                // wait ... (I know that's pretty ugly)
       
                while (conn.isConnected()) {
                        try {
                                Thread.sleep(Long.MAX_VALUE);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }

        // nothing interesting here
        public static void main(String[] args) {
                new SmackTester();
        }

        private void doConnect() {
                // let's connect
                try {
                        conn.connect();
                        conn.login(username, password, "someRessource");
                } catch (XMPPException e) {
                        System.err.println("Login failed!");
                        e.printStackTrace();
                        System.exit(1);
                }
                System.out.println("Login succesful!");
        }

        private void makeConn() {
                ConnectionConfiguration config = new ConnectionConfiguration(server,
                                5222);
                // pass some connection options
                config.setSASLAuthenticationEnabled(true);
                SASLAuthentication.supportSASLMechanism("PLAIN", 0);

                conn = new XMPPConnection(config);
        }

        private Roster makeRoster() {
                Roster roster = conn.getRoster();
                Collection<RosterEntry> entries = roster.getEntries();

                // print out all entries in roster
                System.out.println("---------- entries in roster -----------");
                for (RosterEntry entry : entries) {
                        System.out.println(entry);
                }
                System.out.println("---------- entries in roster -----------");

                // react to changes in roster
                roster.addRosterListener(new RosterListener() {
                        // called methods ...
                        public void entriesDeleted(Collection<String> addresses) {
                                // do stuff
                        }

                        public void entriesUpdated(Collection<String> addresses) {
                                // do stuff
                        }

                        public void presenceChanged(Presence presence) {
                                System.out.println("Presence changed: " + presence.getFrom()
                                                + " " + presence);
                        }

                        public void entriesAdded(Collection<String> arg0) {
                                // do stuff
                        }
                });

                return roster;

        }

        private void chatAction() {
                PacketTypeFilter filter = new PacketTypeFilter(Message.class);
                PacketListener myListener = new PacketListener() {

                        public void processPacket(Packet arg0) {
                                if (arg0 instanceof Message) {
                                        Message msg = (Message) arg0;
                                        System.out.println("Message: " + msg.getFrom() + " "
                                                        + msg.getBody());
                                }
                        }

                };

                // Register the listener.
                conn.addPacketListener(myListener, filter);
        }

        private void doDisconnect() {
                conn.disconnect();
                System.out.println("Disconnected");
        }

}
 
Posted by Sven Pfleiderer in computer | Comments (6) | Trackbacks (0)
Defined tags for this entry: computer, im, jabber, java, opensource, programming, software
Related entries by tags:
  • Mobile devices or: How I Learned to Stop Worrying and Love the iOS
  • The VP8 Video Codec
  • My Bachelor Thesis: Scale the realtime web
  • Distributed contact management using HTTP
  • Gesichtserkennung/Eigenfaces
< Simyo APN Einstellungen | Newsbeuter 2.0 >

Trackbacks
Trackback specific URI for this entry

No Trackbacks

Comments
Display comments as (Linear | Threaded)

*Vielen Dank!
Das hab ich gesucht..

#1 marco (Homepage) on 2009-07-22 15:42 (Reply)

*Na dann bin ich froh, dass ich helfen konnte. :-)

#1.1 pfleidi (Homepage) on 2009-07-22 15:44 (Reply)

*Vielen vielen Dank! :-)

#2 TomTasche on 2009-08-07 21:08 (Reply)

*Nach vielen Stunden hat dies zu einem ersten funktionierenden Chat geführt. Danke :-)

#3 SomeUser on 2010-01-25 05:20 (Reply)

*Hmmm. Irgendwie auch nur ne Zusammenfassung der offiziellen Doku. Versteh auch nicht, wieso man aus der Doku nich deren Beispiele ebenso rauskopieren können soll. Eins, zwei Methodennamen drumherum und das funktioniert auch auf Anhieb. Ich hab selten so eine schöne und verdammt simple Doku gelesen. Kann natürlich auch sein, dass zum Zeitpunkt des Schreibens die Doku noch nicht auf heutigen Stand war.

#4 Anonymous on 2010-06-16 10:26 (Reply)

*Ganz einfach: Ich wollte ein voll funktionsfähiges Beispiel haben und so etwas habe ich damals in der offiziellen Doku nicht gefunden.

Wie man an den anderen Kommentaren erkennen kann, gab es schon anderen, denen der Artikel geholfen hat. Damit ist die Daseinsberechtigung dieses Beispiels ebenfalls geklärt.

#4.1 pfleidi (Homepage) on 2010-06-16 20:39 (Reply)

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
Markdown format allowed
 
 

JavaScript String .fromCharCode

Calendar

« May '12 »
Mo Tu We Th Fr Sa Su
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Quicksearch

Kategorien

  • XML computer
  • XML misc
  • XML web
  • XML zeitgeist


All categories

Archiv

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • Recent...
  • Older...

Feeds

  • XML RSS 2.0 feed
  • ATOM/XML ATOM 1.0 feed
  • XML RSS 2.0 Comments

Links

Retinacast
Shackspace
Yaxim
Radio Tux
Kais Blog
Blumen Pfleiderer
Alk
paxos
filzo
Marc Seeger
polzifer
Moritz Haarmann

Tags

android bad world blog blogging browser changes code comic computer contentmanagement encryption feedreader firefox free fun google gui hardware howto html im jabber java life lighttpd linux linux&unix markup media misc mobile murphy networking newsbeuter opensource picture politics presentation privacy programming regular expression rss ruby s9y scala screenshot sdk security server shortys software stuff tail -f /var/log/life test tool tv unix video web webdesign webwide windows xml zeitgeist

Lizenz

Creative Commons License - Some Rights Reserved