Go Back   Java Programming Forums > Learning Java > Java Code Snippets and Tutorials


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 09-06-2009, 02:10 PM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Post How to Write a simple XMPP (Jabber) client using the Smack API

About XMPP

The Extensible Messaging and Presence Protocol (XMPP) is an open technology for real-time communication, which powers a wide range of applications including instant messaging, presence, multi-party chat, voice and video calls, collaboration, lightweight middleware, content syndication, and generalized routing of XML data.

All offices now days use some kind of instant messaging system to keep in contact with members of staff & clients. In our Office we use Jabber & Pidgin.

Quote:
Originally Posted by igniterealtime.org
Smack is an Open Source XMPP (Jabber) client library for instant messaging and presence. A pure Java library, it can be embedded into your applications to create anything from a full XMPP client to simple XMPP integrations such as sending notification messages and presence-enabling devices.
Using the Smack API we can build a Java application which works in the same way as these popular XMPP clients. This opens up all kinds of possibilities. I am currently working on a bot which will take incoming commands from anyone in the office and in turn perform tasks such as querying a database and returning information.

To begin, download the Smack API from here:

Ignite Realtime: Smack API


Once you have the Smack API downloaded to your computer. Extract all the .jar files.

You now need to include these jar files into your project.

If you use Eclipse you can follow these instructions:

Right click your project > Properties > Java Build Path > Add External Jars.

Now we have the Smack API included within our project, we can start to use the API.

Create a new class called JabberSmackAPI and add the below code. Make sure you update the parts in bold.

Java Code:
import java.util.*;
import java.io.*;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class JabberSmackAPI implements MessageListener{

    XMPPConnection connection;

    public void login(String userName, String password) throws XMPPException
    {
    ConnectionConfiguration config = new ConnectionConfiguration("im.server.here",5222, "Work");
    connection = new XMPPConnection(config);

    connection.connect();
    connection.login(userName, password);
    }

    public void sendMessage(String message, String to) throws XMPPException
    {
    Chat chat = connection.getChatManager().createChat(to, this);
    chat.sendMessage(message);
    }

    public void displayBuddyList()
    {
    Roster roster = connection.getRoster();
    Collection<RosterEntry> entries = roster.getEntries();

    System.out.println("\n\n" + entries.size() + " buddy(ies):");
    for(RosterEntry r:entries)
    {
    System.out.println(r.getUser());
    }
    }

    public void disconnect()
    {
    connection.disconnect();
    }

    public void processMessage(Chat chat, Message message)
    {
    if(message.getType() == Message.Type.chat)
    System.out.println(chat.getParticipant() + " says: " + message.getBody());
    }

    public static void main(String args[]) throws XMPPException, IOException
    {
    // declare variables
    JabberSmackAPI c = new JabberSmackAPI();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String msg;


    // turn on the enhanced debugger
    XMPPConnection.DEBUG_ENABLED = true;


    // Enter your login information here
    c.login("[B]username[/B]", "[B]password[/B]");

    c.displayBuddyList();
   
    System.out.println("-----");
   
    System.out.println("Who do you want to talk to? - Type contacts full email address:");
    String talkTo = br.readLine();
   
    System.out.println("-----");
    System.out.println("All messages will be sent to " + talkTo);
    System.out.println("Enter your message in the console:");
    System.out.println("-----\n");

    while( !(msg=br.readLine()).equals("bye"))
    {
        c.sendMessage(msg, talkTo);
    }

    c.disconnect();
    System.exit(0);
    }

}

When you run this code the Smack Debug window will show.



For more information on what this does and how to use it, see:

Smack: Debugging - Jive Software

The code will then print a list of available contacts. You can select who to talk to and start sending messages to that person.

Here is an example console output:

Quote:
4 buddy(ies):
andyf@im.javaprogrammingforums.com
pault@im.javaprogrammingforums.com
gregd@im.javaprogrammingforums.com
peterm@im.javaprogrammingforums.com
-----
Who do you want to talk to?
kierond@im.javaprogrammingforums.com
-----
All messages will be sent to kierond@im.javaprogrammingforums.com
Enter your message in the console:
-----

Hello kieron!
This is a very simple example of how to use the Smack API. It's a good base for writing your own XMPP client.

For help and a more in depth explanation, see the documentation that comes with the Smack API.



__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote Share this thread on Facebook
Sponsored Links
Java Training from DevelopIntelligence
  #2 (permalink)  
Old 18-06-2009, 06:45 AM
Junior Member
 

Join Date: Jun 2009
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
osmankamil is on a distinguished road
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

hello ,

i am using netbeans 6.5.1 and i have added

smack.jar
smackx.jar
smackx-debug.jar
smackx-jingle.jar

to my project and tried to compile your code

i am getting class not found error in the line below
Quote:
JabberSmack c = new JabberSmack();
Can you help me with that please.. THX
Reply With Quote
  #3 (permalink)  
Old 18-06-2009, 10:32 AM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Hello osmankamil, welcome to the forums.

Sorry, that error was my fault.

Java Code
JabberSmack c = new JabberSmack();
Should be:

Java Code
JabberSmackAPI c = new JabberSmackAPI();
I have updated the code example so it should be fixed. Please try again.
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote
The Following User Says Thank You to JavaPF For This Useful Post:
osmankamil (18-06-2009)
  #4 (permalink)  
Old 18-06-2009, 01:07 PM
Junior Member
 

Join Date: Jun 2009
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
osmankamil is on a distinguished road
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

I have easily created 2 users with openfire.
I am using pidgin as one of my clients and your example code for the other client.

My question is about the way XMPP works , should i get permission from a client to be added to his/her list ? Because i can not send any messages to my account which is logged in from pidgin even it looks online when i check from openfire admin console.

I tried using two pidgin softwares , and tried to add each other as buddies. But no request was sent from one to another. However if i make both my account to join a chat room . They can see and talk to each other.

Any help would be appriciated.
Thanks
Reply With Quote
  #5 (permalink)  
Old 19-06-2009, 01:36 PM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Hello osmankamil.

To be honest, I am not all that familiar with XMPP. We use Pidgin here at work but I am not responsible for creating or managing accounts. I started messing around with the Java Smack API because someone else here was working on a PHP version.

I know the client does work because I have used it to send messages to another Pidgin user who was already on my list. I haven't adding a new user myself.

I'm thinking this problem could be because you are running 2 clients on the same PC? Have you tried messaging the Pidgin client on another machine?
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote
  #6 (permalink)  
Old 19-01-2010, 05:59 AM
Junior Member
 

Join Date: Jan 2010
Posts: 3
Thanks: 0
Thanked 1 Time in 1 Post
jch02140 is on a distinguished road
Question Re: How to Write a simple XMPP (Jabber) client using the Smack API

I tried running the sample above with openfire installed in the same machine but I got this result...

Quote:
javax.net.ssl.SSLException: Received fatal alert: internal_error
at com.sun.net.ssl.internal.ssl.Alerts.getSSLExceptio n(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLExceptio n(Alerts.java:136)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAle rt(SSLSocketImpl.java:1682)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRec ord(SSLSocketImpl.java:932)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.perform InitialHandshake(SSLSocketImpl.java:1112)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHa ndshake(SSLSocketImpl.java:1139)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHa ndshake(SSLSocketImpl.java:1123)
at org.jivesoftware.smack.XMPPConnection.proceedTLSRe ceived(XMPPConnection.java:1258)
at org.jivesoftware.smack.PacketReader.parsePackets(P acketReader.java:313)
at org.jivesoftware.smack.PacketReader.access$000(Pac ketReader.java:44)
at org.jivesoftware.smack.PacketReader$1.run(PacketRe ader.java:76)
java.lang.IllegalStateException: Not connected to server.
at org.jivesoftware.smack.XMPPConnection.sendPacket(X MPPConnection.java:729)
at org.jivesoftware.smack.NonSASLAuthentication.authe nticate(NonSASLAuthentication.java:70)
at org.jivesoftware.smack.SASLAuthentication.authenti cate(SASLAuthentication.java:335)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:349)
at simplechat.JabberSmackAPI.login(JabberSmackAPI.jav a:44)
at simplechat.JabberSmackAPI.main(JabberSmackAPI.java :107)
Exception in thread "main" java.lang.IllegalStateException: Not connected to server.
at org.jivesoftware.smack.XMPPConnection.sendPacket(X MPPConnection.java:729)
at org.jivesoftware.smack.NonSASLAuthentication.authe nticate(NonSASLAuthentication.java:70)
at org.jivesoftware.smack.SASLAuthentication.authenti cate(SASLAuthentication.java:345)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:349)
at simplechat.JabberSmackAPI.login(JabberSmackAPI.jav a:44)
at simplechat.JabberSmackAPI.main(JabberSmackAPI.java :107)
The console is listening to the following address:

http://<computer_id>:9090
https://<computer_id>:9091

I tried using the address, 127.0.0.1 and localhost but all return errors... I am not sure what went wrong...

Last edited by jch02140; 19-01-2010 at 06:03 AM.
Reply With Quote
  #7 (permalink)  
Old 26-04-2010, 03:53 PM
Junior Member
 

Join Date: Apr 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Matija is on a distinguished road
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Quote:
Originally Posted by jch02140 View Post
I tried running the sample above with openfire installed in the same machine but I got this result...



The console is listening to the following address:

http://<computer_id>:9090
https://<computer_id>:9091

I tried using the address, 127.0.0.1 and localhost but all return errors... I am not sure what went wrong...
how to add new buddyes to my list of friends? Thanks
Reply With Quote
  #8 (permalink)  
Old 26-04-2010, 05:17 PM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Quote:
Originally Posted by jch02140 View Post
I tried running the sample above with openfire installed in the same machine but I got this result...



The console is listening to the following address:

http://<computer_id>:9090
https://<computer_id>:9091

I tried using the address, 127.0.0.1 and localhost but all return errors... I am not sure what went wrong...
Did you use the above code example exactly? If not, please post your version.

It must be down to the XMPP configuration
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote
  #9 (permalink)  
Old 03-05-2010, 02:07 PM
Junior Member
 

Join Date: Apr 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Matija is on a distinguished road
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Did anybody had this problem: I can communicate from client to client in both ways, but i always see that my smack client is NOT AUTHORIZED (my second client is Pidgin client)...why is that? please help. Thank you!!!
Reply With Quote
  #10 (permalink)  
Old 05-05-2010, 11:36 AM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Default Re: How to Write a simple XMPP (Jabber) client using the Smack API

Quote:
Originally Posted by jch02140 View Post
I tried running the sample above with openfire installed in the same machine but I got this result...



The console is listening to the following address:

http://<computer_id>:9090
https://<computer_id>:9091

I tried using the address, 127.0.0.1 and localhost but all return errors... I am not sure what went wrong...
Try putting the server location where it says Work in the code.
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote
Reply

Tags
jabber, smack api, xmpp

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] web client 5723 File I/O & Other I/O Streams 8 10-06-2009 09:44 PM
[SOLVED] simple change to a boolean value in a method call help... rptech Object Oriented Programming 3 20-05-2009 10:48 AM
Yo! Stuck making a simple game rojroj Java Theory & Questions 3 02-04-2009 03:24 PM
Looking for a programmer to make a simple program. GrosslyMisinformed Paid Java Projects 3 27-01-2009 07:33 PM
How to write a file using Java JavaPF Java Code Snippets and Tutorials 0 13-08-2008 11:45 AM


100 most searched terms
Search Cloud
2d arraylist java actionlistener actionlistener in java actionlistener java addactionlistener addactionlistener in java addactionlistener java applications of oops could not create java virtual machine xp double format java double to int double to int java double to integer in java double to integer java eclipse shortcut keys eclipse tutorial for beginners exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double java get mouse position java java 2d arraylist java actionlistener java addactionlistener java convert list to map java double format java double formatting java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programming forum java programming forums java programming help java sendkeys java two dimensional arraylist java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton actionlistener jtextarea font jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream programming mutators and generics two dimensional arraylist java writing ipod apps

All times are GMT. The time now is 09:21 AM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.