-
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.
Code Java:
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.
http://javaprogrammingforums.com/images/smackdebug.jpg
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:
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.
-
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
-
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.
Code :
[B]JabberSmack c = new JabberSmack();[/B]
Should be:
Code :
[B]JabberSmackAPI c = new JabberSmackAPI();[/B]
I have updated the code example so it should be fixed. Please try again.
-
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
-
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?
-
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...
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Quote:
Originally Posted by
jch02140
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
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Quote:
Originally Posted by
jch02140
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 #-o
-
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!!!
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Quote:
Originally Posted by
jch02140
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.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Hi i'm new in this!
I'm interested in how to make a presence for this example of client that could be changed like away,online,do not disturb.
Thank you very much!
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Hi I am new in java. So what i ask might sound silly. Anyway in here
Quote:
ConnectionConfiguration config = new ConnectionConfiguration("im.server.here", 5222, "Work");
The way i wrote is
Quote:
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222);
is it ok??
And in your code
Quote:
// Enter your login information here
c.login("username", "password");
Which login info should i use?? Is it the one i created with openfire or my gmail account?? I am very confused. And many many thanks for the code :)
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Code :
ConnectionConfiguration config = new ConnectionConfiguration("im.server.here", 5222, "Work");
Make sure im.server.here is set to your Jabber Server address. You may also need to replace Work with your Jabber server address.
As for:
Code :
// Enter your login information here
c.login("username", "password");
You need to enter the login and password information for the chat account you use.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Thanks for your reply. When i run your code smack debug window shows perfectly. But it doesnt print any list of available cotact. I make one other gmail accoutn online but it doesnt show it. And i tried to message me from that account but it shows im offline.
And there is an error message shows after running the code
Quote:
run:
Exception in thread "main" SASL authentication failed using mechanism DIGEST-MD5:
at org.jivesoftware.smack.SASLAuthentication.authenti cate(SASLAuthentication.java:325)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPCo nnection.java:349)
at RunJabberSmackAPI.login(RunJabberSmackAPI.java:23)
at RunJabberSmackAPI.main(RunJabberSmackAPI.java:68)
i used my gmail account username password to login. i replaced "im.server.here" with "jabber.org" and "work" with "jabber.org".
I dont know what is the problem :(
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
I don't think Jabber.org is your jabber server. You need to have a server installed somewhere and link to it that way..
For example, Ignite Realtime: Openfire Server
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
I did like this
Quote:
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org",5222,"localho st");
Here localhost is my host. Now everything works fine but when smack debug window shows it shows that it has sent presence which is fine. But it shows the presence type "unavilable". What is wrong in my code :(
my code
Quote:
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 RunJabberSmackAPI implements MessageListener{
XMPPConnection connection;
public void login(String userName, String password) throws XMPPException
{
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org",5222,"localho st");
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
RunJabberSmackAPI c = new RunJabberSmackAPI();
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("admin", "admin"); // I created this user with openfire.
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);
}
}
It also shows exceptions
Quote:
run:
org.xmlpull.v1.XmlPullParserException: could not determine namespace bound to element prefix stream (position: START_DOCUMENT seen <stream:error>... @1:14)
at org.xmlpull.mxp1.MXParser.parseStartTag(MXParser.j ava:1816)
at org.xmlpull.mxp1.MXParser.parseProlog(MXParser.jav a:1479)
at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1 395)
at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
at org.jivesoftware.smack.PacketReader.parsePackets(P acketReader.java:368)
at org.jivesoftware.smack.PacketReader.access$000(Pac ketReader.java:44)
at org.jivesoftware.smack.PacketReader$1.run(PacketRe ader.java:76)
Exception in thread "main" Connection failed. No response from server.:
at org.jivesoftware.smack.PacketReader.startup(Packet Reader.java:164)
at org.jivesoftware.smack.XMPPConnection.initConnecti on(XMPPConnection.java:945)
at org.jivesoftware.smack.XMPPConnection.connectUsing Configuration(XMPPConnection.java:904)
at org.jivesoftware.smack.XMPPConnection.connect(XMPP Connection.java:1415)
at RunJabberSmackAPI.login(RunJabberSmackAPI.java:22)
at RunJabberSmackAPI.main(RunJabberSmackAPI.java:68)
i created user admin with openfire. I tried with gmail account user because i m confused which user account should i use.The one i created with openfire or my actual gmail account. But trying with both give the same result.
Thank You.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Code :
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org",5222,"[B]localho st[/B]");
Should be
Code :
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org",5222,"[B]localhost[/B]");
??
Try replacing jabber.org with localhost or 127.0.0.1 as well.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Well its written localhost in my code. Just a copy mistake in here.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Thank You so very much chaging to 127.0.0.1 totally worked :D .
I have opened two account in openfire and im logged in on those account with your code . Not one of them has any buddy. How can i add those account as buddies to chat .
And again many thanks for your help.
EDIT: I added budies from openfire admin console. They are added and the budies are shown . But if i send any message then it sends successfully but then receive error
Code XML:
<message id="LM8uW-5" to="nayim@sust-2a24ea2754/Smack" from="admin@example.com" type="error">
<thread>DA50z0</thread>
<error code="404" type="CANCEL">
<remote-server-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
</error>
</message>
Where nayim@example.com is sender and admin@example.com is receiver.
Why is it happeining ?? :(
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
I couldn't login to local ejabberd server using smack API. I could connect Miranda IM to ejabberd local server but whenever I try to do the same using smack, it throws this exception -
Exception in thread "main" SASL authentication failed using mechanism DIGEST-MD5:
at org.jivesoftware.smack.SASLAuthentication.authenti cate(SASLAuthentication.java:325)
Following is the used java class. It is able to connect but not able to login. I also tried setting XMPPConnection.DEBUG_ENABLED = true and config.setSASLAuthenticationEnabled(false), but in vain.
Code :
public class ConnectionToLocalServer {
private static String username = "admin@localhost";
private static String password = "genespring123";
ConnectionConfiguration connConfig;
XMPPConnection connection;
public ConnectionToLocalServer() throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("localhost",5222);
connection = new XMPPConnection(config);
connection.connect();
System.out.println("CONNECTED..");
connection.login(username, password);
System.out.println("LOGED IN..");
}
public void sendMessage(String to, String message ) {
Message msg = new Message(to, Message.Type.chat);
msg.setBody(message);
connection.sendPacket(msg);
System.out.println("SENT MSG..");
}
public void disconnect() {
connection.disconnect();
}
public static void main(String[] args) throws XMPPException {
ConnectionToLocalServer messageSender = new ConnectionToLocalServer();
messageSender.sendMessage("support1@localhost","hi ss");
messageSender.disconnect();
}
}
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Can somebody tell me the solution of my problem please. It is written above. I desperately need help :(
-
How to Write a simple XMPP (Jabber) client using the Smack API
I have tried this code and worked perfectly when i run it as a java application......then i created an android project and did through a button what is done through main. on clicking a button i invoked all the functions invoked through main.........but it fails in connection.connect().
Can you please tell me whats the solution for this??
Thanks
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Quote:
Originally Posted by
sbhukar
I have tried this code and worked perfectly when i run it as a java application......then i created an android project and did through a button what is done through main. on clicking a button i invoked all the functions invoked through main.........but it fails in connection.connect().
Can you please tell me whats the solution for this??
Thanks
Could you please start a new thread and post all of your code? It will really help us diagnose your problem.
Thank you.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Quote:
Originally Posted by
calicratis19
Thank You so very much chaging to 127.0.0.1 totally worked :D .
I have opened two account in openfire and im logged in on those account with your code . Not one of them has any buddy. How can i add those account as buddies to chat .
And again many thanks for your help.
EDIT: I added budies from openfire admin console. They are added and the budies are shown . But if i send any message then it sends successfully but then receive error
Code XML:
<message id="LM8uW-5" to="nayim@sust-2a24ea2754/Smack" from="admin@example.com" type="error">
<thread>DA50z0</thread>
<error code="404" type="CANCEL">
<remote-server-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
</error>
</message>
Where
nayim@example.com is sender and
admin@example.com is receiver.
Why is it happeining ?? :(
Could you also please start a new thread and post all of your code? Thank you.
-
Re: How to Write a simple XMPP (Jabber) client using the Smack API
Hello,
how can i use single sign on to authenticate the client?
thanks!