jump to navigation

How to write your own IM program/GTalk client in Java August 7, 2008

Posted by razasayed in programming.
Tags: , , ,
trackback

Here i will show you how you can write your own simple gtalk client using an open source java library called “Smack“. Smack is a cross-platform Open Source XMPP (Jabber) client library for instant messaging and presence , and as you will see it actually makes writing your own client to connect to any jabber service a breeze 🙂 . The library is extremely versatile but to keep things simple, here we develop a program to exchange messages with a buddy of yours in GTalk.

But before we start, what the heck is XMPP and Jabber ? . If you already know this you can skip to the next part.

You see there are many, many IM clients around. Companies such as Microsoft, and Yahoo provide IM services based on proprietary messaging protocols, and also provide popular client software (Microsofts MSN Messenger and Yahoos Yahoo Messenger) using these protocols. Many third-party clients also work with these protocols. However, these protocols remain proprietary and closed, which tends to make them difficult to work with for a developer.

Jabber is an open, XML-based “standard” for instant messaging and is an open source alternative to the proprietary messaging protocols . Jabber uses XMPP (Extensible Messaging and Presence Protocol), which is an “XML based protocol” , for transferring messages. Since the Jabber messages are transmitted in XML form it makes it easy for developers to work with them. Googles instant messaging service uses the Jabber protocol .

OK, now lets get our hands dirty with some code, shall we ? 🙂 . Alright, here we go .

Step 1) To start with download the Smack API

Step 2) Create a folder for your project. Create a lib subfolder . Unzip the downloaded zip file and copy the following files to the lib subfolder : smack.jar, smackx.jar,smackx-debug.jar.If you want you can also copy these files to any other location of your choice and then add the location of these files to the classpath.

Step 3) Now we write the actual code for implementing our gtalk client. To do that first create a file MyGTalkClient.java in your main folder, or anywhere else if you have added the location of the jar files to your classpath.

Step 3.1) The first step is connecting to the GTalk service  The code below does that :


ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
XMPPConnection connection = new XMPPConnection(config);
connection.connect(); /* Connect to the XMPP server  */
connection.login("username","password"); /* Login to the IM service */

“talk.google.com” is the host. 5222 is the port number and “gmail.com” is the service name.

Step 3.2) To send a message to a buddy we use the Chat class as follows :

Chat chat = connection.getChatManager().createChat("friend@gmail.com",new MyGtalkClient());
chat.sendMessage("Hi"); /* Send the message  */

The first argument to createChat method is obviously the email id of your buddy in GTalk . The second argument is an instance of a class that implements the org.jivesoftware.smack.MessageListener interface . This listener interface receives incoming messages and calls its processMessage method to process the message.

Step 3.3) Now, the next step is making sure that we receive the messages that our friend sends . To do that we implement the processMessage method of the MessageListener interface as follows :


public void processMessage(Chat chat,Message message) /*Callback method from MessageListener interface . It is called when a message is received */
{
        System.out.println("Received message: " + message.getBody());
}

Step 3.4) After you are done chatting with your friend you can disconnect from the server as follows :


connection.disconnect() ; //Disconnect 

There we are . A simple bare-bones Jabber client to connect to the GTalk service is ready ! .The final code looks like this .

Step 4) If you have not added the locations of the jar files to the classpath , you can compile and run your chat client as follows :


javac -cp lib\smack.jar;lib\smackx.jar;lib\smackx-debug.jar MyGTalkClient.java

java -cp lib\smack.jar;lib\smackx.jar;lib\smackx-debug.jar;. MyGTalkClient
(Note the ;. at the end of the classpath)

Thats all there is to it ! . From here on you can explore the API, and try to come up with really cool ideas for using instant messaging and presence in your applications.

Happy Hacking !! 🙂

Comments»

1. sweety - August 12, 2008

Hi,
I am mcs studet and done the same coding for chatclient
but output is like

****Welcome to MyGtalkClient****
****Enter your message, one per line . To stop chat enter stop****
Exception in thread “Smack Packet Reader (0)” java.lang.ExceptionInInitializerError
at org.jivesoftware.smackx.provider.DelayInformationProvider.parseExtension(DelayInformationProvider.java:51)
at org.jivesoftware.smack.util.PacketParserUtils.parsePacketExtension(PacketParserUtils.java:378)
at org.jivesoftware.smack.util.PacketParserUtils.parsePresence(PacketParserUtils.java:204)
at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:278)
at org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:44)
at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:76)
Caused by: java.lang.NullPointerException
at java.util.TimeZone.parseCustomTimeZone(TimeZone.java:780)
at java.util.TimeZone.getTimeZone(TimeZone.java:484)
at java.util.TimeZone.getTimeZone(TimeZone.java:478)
at org.jivesoftware.smackx.packet.DelayInformation.(DelayInformation.java:51)
… 6 more

after trial of continous 3-4 days i m not successful
raza please help me
i used redhat4

2. razasayed - August 12, 2008

Hi sweety, thanks for stopping by my blog.Well, where are you entering the messages you want to send ?. You are supposed to enter them in the console window, not in the debug window that opens if you have XMPPConnection.DEBUG_ENABLED = true; in your code..
Also, are you able to run the program successfully on a windows machine or some other linux machine ?. If yes, there could be some problem with the java settings on the redhat.machine where you are running the program.

3. sweety - August 13, 2008

Thanks a lot raza
I entered messages on console only bt check status on debug window
i want to execute it only on linux .i will try for window.
why this exception arise ,any idea?
if u know something about settings of linux reply me
good day

4. razasayed - August 13, 2008

In the code try replacing :

while( !(msg=br.readLine()).equals("stop")) 

with

while(!"stop".equals(msg=br.readLine())) 

See if it works then.

5. rakesh meena - August 23, 2008

hi, I am rakesh doing MCA form NIT.
I am Implementing a server and client program in java.So plz tell me that how I establish connection between server and client????
using IP address???
and other way………..

6. razasayed - August 24, 2008

Hi rakesh, well you will need to do something called “Socket Programming” . You can find tons of information on it . Just ask Google 🙂

7. Daniel gibson - September 6, 2008

Heya guys – Has any 1 got the code to make some sort of connection/bot for msn at all

Please email me if you have or know how to

thanks

8. razasayed - September 7, 2008

For MSN bot you could check out http://msn-bot.sourceforge.net/ , its python code…hope that helps.

9. Karthik - September 10, 2008

Hi razasayed,

I am trying to run ur code in windows xp. Could you please tell me which one should i download from Smack API dowload link?

10. razasayed - September 10, 2008

You need to download the Smack 3.0.4 xmpp client library . Heres the direct link : http://www.igniterealtime.org/downloads/download-landing.jsp?file=smack/smack_3_0_4.zip .

11. seb - September 19, 2008

Hi Raza,

Just wanted to say thank you for this gentle introduction to the Smack API. I was looking for an XMPP API for java, and you provided the exact starting point I needed : short and well-written.

Thanks again.

12. razasayed - September 19, 2008

Hi seb, im glad you liked the post 🙂

13. john - September 29, 2008

This example is really nice because it works as written. SMACK seems like a really great basis for writing clients. I’ve seen a few other libraries (like xmpp4js and others) but I haven’t gotten them to work. I wish someone explained them as clearly.

14. Anisa Ragalo - October 12, 2008

Hi Raza,

Thank you so much for this blog. I am trying to run MyGTalkClient.java with smack_3_0_4, the latest version of Smack on ubuntu but I get the following error:

MyGTalkClient.java:7: cannot access org.jivesoftware.smack.MessageListener
bad class file: lib/smack.jar(org/jivesoftware/smack/MessageListener.class)
class file has wrong version 49.0, should be 48.0
Please remove or make sure it appears in the correct subdirectory of the classpath.
public class MyGTalkClient implements MessageListener
^
1 error

I dont know what the problem could be since I assume you were using the same libraries. Please help me Raza. Thank you in advancd

15. razasayed - October 12, 2008

Hi Anisa, thanks for stopping by my blog . Make sure that the version of the jre you are using is the same as that of javac . Type java -version at the terminal to verify this. If they are different you may have to update your PATH variable . If you still have a problem then, try running the program by having the jar files at the same location where your .java file is and use the commands I specified in my post to compile and run the program . Hope that helps

16. Saminda - October 20, 2008

hi,
thanx for info on how to create gtalk client. but i hit a wall when it came to group chats. do u know hw to accept group invitation sent by gtalk?? would be grateful if u could help. i’ve being combing the net for any suggestion for a couple of days nw.

Thanx man

17. Harish - November 8, 2008

well good!… can i know how to create them in PHP? is there any solution for? wat is IM API?

18. Vivek - November 12, 2008

I’m unable to connect. Getting below mentioned exception. I don’t think its because of firewall as I’m able to login to my gtalk.
Could u suggest what might be wrong?

Exception in thread “main” XMPPError connecting to talk.google.com:5222.: remote
-server-error(502) XMPPError connecting to talk.google.com:5222.
— caused by: java.net.ConnectException: Connection timed out: connect
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPC
onnection.java:830)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:127
6)
at MyGTalkClient.main(MyGTalkClient.java:26)
Nested Exception:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:520)
at java.net.Socket.connect(Socket.java:470)
at java.net.Socket.(Socket.java:367)
at java.net.Socket.(Socket.java:180)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPC

19. mohan - January 20, 2009

Well…How to implement this in PHP or Perl….

20. Samrat - February 10, 2009

Hi razza…..nice work done man……..but i m getting so 11 errors while running the program…..and just got confused…..
i m using J2SE 1.3…
Created 1 folder on desktop
den one subfolder lib
kept all necessary jar files in dat lib folder….
den created MyGTalkClient.java using ur given code…
set the class path C:\Documents and Settings\Sam\Desktop\GTalk\lib;

den run d programme…and errors are

C:\Documents and Settings\Sam\Desktop\GTalk>javac MyGTalkClient.java
MyGTalkClient.java:4: package org.jivesoftware.smack does not exist
import org.jivesoftware.smack.*;
^
MyGTalkClient.java:5: package org.jivesoftware.smack.packet does not exist
import org.jivesoftware.smack.packet.*;
^
MyGTalkClient.java:7: cannot resolve symbol
symbol : class MessageListener
location: class MyGTalkClient
public class MyGTalkClient implements MessageListener
^
MyGTalkClient.java:10: cannot resolve symbol
symbol : class Chat
location: class MyGTalkClient
public void processMessage(Chat chat,Message message) /*Callback method from
MessageListener interface . It is called when a message is received */
^
MyGTalkClient.java:10: cannot resolve symbol
symbol : class Message
location: class MyGTalkClient
public void processMessage(Chat chat,Message message) /*Callback method from
MessageListener interface . It is called when a message is received */
^
MyGTalkClient.java:16: cannot resolve symbol
symbol : class XMPPException
location: class MyGTalkClient
public static void main(String [] args) throws XMPPException,IOException
^
MyGTalkClient.java:22: cannot resolve symbol
symbol : class ConnectionConfiguration
location: class MyGTalkClient
ConnectionConfiguration config = new ConnectionConfiguration(“talk.googl
e.com”,5222,”gmail.com”);
^
MyGTalkClient.java:22: cannot resolve symbol
symbol : class ConnectionConfiguration
location: class MyGTalkClient
ConnectionConfiguration config = new ConnectionConfiguration(“talk.googl
e.com”,5222,”gmail.com”);
^
MyGTalkClient.java:23: cannot resolve symbol
symbol : class XMPPConnection
location: class MyGTalkClient
XMPPConnection connection = new XMPPConnection(config);
^
MyGTalkClient.java:23: cannot resolve symbol
symbol : class XMPPConnection
location: class MyGTalkClient
XMPPConnection connection = new XMPPConnection(config);
^
MyGTalkClient.java:29: cannot resolve symbol
symbol : class Chat
location: class MyGTalkClient
Chat chat = connection.getChatManager().createChat(“friend@gmail.com”,ne
w MyGTalkClient()); /* Replace friend , with your buddies id */
^
11 errors

21. Samrat - February 10, 2009

Hi razza…..nice work done man……..but i m getting so 11 errors while running the program…..and just got confused…..
i m using J2SE 1.3…
Created 1 folder on desktop
den one subfolder lib
kept all necessary jar files in dat lib folder….
den created MyGTalkClient.java using ur given code…
set the class path C:\Documents and Settings\Sam\Desktop\GTalk\lib;

den run d programme…and errors are

C:\Documents and Settings\Sam\Desktop\GTalk>javac MyGTalkClient.java
MyGTalkClient.java:4: package org.jivesoftware.smack does not exist
import org.jivesoftware.smack.*;
^
MyGTalkClient.java:5: package org.jivesoftware.smack.packet does not exist
import org.jivesoftware.smack.packet.*;
^
MyGTalkClient.java:7: cannot resolve symbol
symbol : class MessageListener
location: class MyGTalkClient
public class MyGTalkClient implements MessageListener
^
MyGTalkClient.java:10: cannot resolve symbol
symbol : class Chat
location: class MyGTalkClient
public void processMessage(Chat chat,Message message) /*Callback method from
MessageListener interface . It is called when a message is received */
^
MyGTalkClient.java:10: cannot resolve symbol
symbol : class Message
location: class MyGTalkClient
public void processMessage(Chat chat,Message message) /*Callback method from
MessageListener interface . It is called when a message is received */
^
MyGTalkClient.java:16: cannot resolve symbol
symbol : class XMPPException
location: class MyGTalkClient
public static void main(String [] args) throws XMPPException,IOException
^
MyGTalkClient.java:22: cannot resolve symbol
symbol : class ConnectionConfiguration
location: class MyGTalkClient
ConnectionConfiguration config = new ConnectionConfiguration(”talk.googl
e.com”,5222,”gmail.com”);
^
MyGTalkClient.java:22: cannot resolve symbol
symbol : class ConnectionConfiguration
location: class MyGTalkClient
ConnectionConfiguration config = new ConnectionConfiguration(”talk.googl
e.com”,5222,”gmail.com”);
^
MyGTalkClient.java:23: cannot resolve symbol
symbol : class XMPPConnection
location: class MyGTalkClient
XMPPConnection connection = new XMPPConnection(config);
^
MyGTalkClient.java:23: cannot resolve symbol
symbol : class XMPPConnection
location: class MyGTalkClient
XMPPConnection connection = new XMPPConnection(config);
^
MyGTalkClient.java:29: cannot resolve symbol
symbol : class Chat
location: class MyGTalkClient
Chat chat = connection.getChatManager().createChat(”friend@gmail.com”,ne
w MyGTalkClient()); /* Replace friend , with your buddies id */
^
11 errors

22. Samrat - February 13, 2009

Hey razza my all errors are solved but while running the programme i getting following error.

———- Run ———-
Exception in thread “main” SASL authentication failed:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:209)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:341)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:301)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:283)
at MyGTalkClient.main(MyGTalkClient.java:25)

23. harrylynn - February 14, 2009

Hi Raza,

First of all, This is a great post !! Keep up the good work. I really admire what you have done on this post. I’m a computer science student, in my final year. I’m thinking of writing an application like Gtalk. Basically, the idea is just another client and server IM program by using only Java. I’m not really familiar with Java but I did a bit of C programming. Do you think it could be done using just Java API ? Umm Do i need to read through J2EE ? Please guide me a bit and if you dun mind then please provide me a few links where I can look up the information relvant to my project. Anyway, Great job what you’ve done. I’ve learnt a lot from this site.

24. dayssam - May 6, 2009

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

/**
*
* @author moha
*/
public class MyGtalkClient implements MessageListener {

public void processMessage(Chat chat,Message message) {
/*Callback method from MessageListener interface .
It is called when a message is received */

System.out.println(“Received message: ” + message.getBody());
}

public static void main(String [] args) throws XMPPException,IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

/*Login to GTalk service*/
ConnectionConfiguration config = new ConnectionConfiguration (
“talk.google.com”,
5222,
“gmail.com”);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(false);
XMPPConnection connection = new XMPPConnection(config);

connection.connect(); /* Connect to the XMPP server */

connection.login(“m.habou”,”1986moha”);
/*Enter your username & password to login to the gtalk service */
Chat chat = connection.getChatManager().createChat(“kuljayster@gmail.com”,new MyGtalkClient());
chat.sendMessage(“Hi”);
System.out.println(” ****Welcome to MyGtalkClient**** “);
System.out.println(“****Enter your message, one per line .”+
“To stop chat enter stop****”);
String msg;
while( !(msg=br.readLine()).equals(“stop”)) {
chat.sendMessage(msg); //Send the message
}

connection.disconnect() ; //Disconnect
}
}

is working

thx alooot

abdul basith m - June 10, 2009

ur are great..

Vineet Sharma - September 14, 2010

Thanks buddy

25. abdulbasithm - May 21, 2009

hi advance thanks….
i need of the java source code…..

26. atul - June 2, 2009

hi nice work…..

dayssam….ur code is compiling
but on running i am getting following runtime exception
Exception in thread “main” java.lang.NoClassDefFoundError: MyGTalkClient (wrong
name: MyGtalkClient)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)

any idea ?? ……i have entered right user name and passwd..

27. vishnu - July 25, 2009

sir how to see the contactlist

28. saurabh - August 21, 2009

hi razasayed,
i m working on android mobile .i want to make a program which connect the gtalk ,but i have some problem in this code
ConnectionConfiguration connConfig =
new ConnectionConfiguration(“talk.google.com”,5222,”gmail.com”);
XMPPConnection connection = new XMPPConnection(connConfig);

try {
connection.connect();
Log.i(“XMPPClient”, “[SettingsDialog] Connected to ” + connection.getHost());
} catch (XMPPException ex) {
Log.e(“XMPPClient”, “[SettingsDialog] Failed to connect to ” + connection.getHost());
xmppClient.setConnection(null);
}
try {
connection.login(“saurabhdiamond”,”************”);
Log.i(“XMPPClient”, “Logged in as ” + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.e(“XMPPClient”, “[SettingsDialog] Failed to log in as ” + username);
xmppClient.setConnection(null);
}

but the error is
E/dalvikvm( 719): Could not find method javax.security.sasl.SaslClient.hasIniti
alResponse, referenced from method org.jivesoftware.smack.sasl.SASLMechanism.aut
henticate
W/dalvikvm( 719): VFY: unable to resolve interface method 1150: Ljavax/security
/sasl/SaslClient;.hasInitialResponse ()Z

29. vaibhaw - August 30, 2009

how to make a connection when we are using a proxy network ???

akshay - October 7, 2009

use System.setproxy

30. akshay - October 7, 2009

can i use voice as well?I want to use voice chat too in my gt

31. Harsha - January 5, 2010

Hi Raza,
Very informative and very nice, Thanks a lot for this information,
I am able to login to Gtalk, but when i try programatically using your code, i get the below error, can you please help me out?

32. Harsha - January 5, 2010

Sorry, i forgot to paste the trace . Here it is……..
MPPError connecting to talk.google.com:5222.: remote-server-error(502) XMPPError connecting to talk.google.com:5222.
— caused by: java.net.ConnectException: Connection refused: connect
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:900)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at com.harsha.changeGtalkStatus.ChangeStatusMsg.changeStatus(ChangeStatusMsg.java:32)
at com.harsha.changeGtalkStatus.ChangeStatusMsg.main(ChangeStatusMsg.java:52)
Nested Exception:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:28)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:888)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at com.harsha.changeGtalkStatus.ChangeStatusMsg.changeStatus(ChangeStatusMsg.java:32)
at com.harsha.changeGtalkStatus.ChangeStatusMsg.main(ChangeStatusMsg.java:52)

33. ADNAN - February 15, 2010

I want to add chat room in my application help me
if you have any material
adnanghazanfar@rocketmail.com

34. umashankar - April 7, 2010

Hi……nice example…….If I want to add user interface for it……..or if want to make web based what should I do …….I still want to use java smack api for messaging. razasayed ..please help me
Thank you

35. Nandhakumar - May 17, 2010

Hi,

Thanks in Advance.

Now I am giving detail description about the problem.
XMPP Client program: It should running in mobile device,
It contains,
1. Login screen, mobile users login into the application by using the openfire server users accounts
2. It receive the broadcasted message from the openfire server and display it in mobile screen.
3. The user able to send message to the server.
Please Send the code for this program. I am eagerly waiting for your reply.
I am Using Netbeans 6.8 for developing xmpp client program

If U feel not enough this description then I will send elaborate.

36. mohit singhal - June 11, 2010

hello sir ,
i am working an project on to made GTalk. i have a problem in to add contacts

37. Saswat - June 16, 2010

hi,

gtalk is not connected now.Previously your code as worked fine but now it throws 502-remote server error.

Please help me to solve it !

thank you .

38. Ahmed - July 28, 2010

Hi Razasayed,

Thank you for the stuff.

After i read all the messages, there is no response from u since Oct 2008. Is this blog still live? Can we post questions?????

Rgds,
Ahmed

39. abhinav - August 12, 2010

I was curious if any one got smack working with google talk voice calls??

40. mohit singhal - August 16, 2010

hello sir,
i am student of B.Tech i am doing Gtalk project i which i have a problem to show gmail contact on my gtalk design .please help me. i am sending ding my code
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.List;
import java.util.List;
import java.util.List;
import java.util.List;
import javax.swing.JOptionPane;

import org.jivesoftware.smack.ConnectionConfiguration;
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.Packet;
import org.jivesoftware.smack.packet.Presence;

public class chat {

static XMPPConnection connection;
static Presence presence;
public Collection list;
private static Packet Presence(Presence.Mode dnd) {
throw new UnsupportedOperationException(“Not yet implemented”);
}
/*public static void main (String arg[]) throws XMPPException, IOException,InterruptedException
{

presence=new Presence(Presence.Type.available);
connection.sendPacket(presence);
Message msg=new Message(“ankurlnmiit@gmail.com”,Message.Type.chat);
msg.setBody(“hi”);
connection.sendPacket(msg);

}*/

public void gtalk_login(String user , String pass) throws IOException {
ConnectionConfiguration config=new ConnectionConfiguration(“talk.google.com”,5222,”gmail.com”);
connection=new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {
// Can’t be Connected
JOptionPane.showMessageDialog(null, “Connection Error”, “Can’t Be Connected”, JOptionPane.ERROR_MESSAGE);

//e.printStackTrace();
}
try {
connection.login(user,pass);
} catch (XMPPException e) {
JOptionPane.showMessageDialog(null, “Username or Password Incorrect”, “Can’t Be Login”,JOptionPane.WARNING_MESSAGE);

//e.printStackTrace();
}

presence=new Presence(Presence.Type.available);
connection.sendPacket(presence);

JOptionPane.showMessageDialog(null, “OK”, “Successfully Connected”, JOptionPane.INFORMATION_MESSAGE );

Gtalkframe.fa();
list=contact();
//System.in.read();

}
public static void avail()
{
presence = new Presence(Presence.Type.available,”hi” , 100, Presence.Mode.available);
connection.sendPacket(presence);
}
@SuppressWarnings(“empty-statement”)
public static void idle()
{
//System.out.println(“hi “+ presence.getMode());
presence = new Presence(Presence.Type.available,”hi” , 100, Presence.Mode.away);
// presence=new Presence(Presence.Mode.away);
connection.sendPacket(presence);

}
public static void busy()
{
presence = new Presence(Presence.Type.available,”hi” , 100, Presence.Mode.dnd);
// presence=new Presence(Presence.Mode.away);
connection.sendPacket(presence);
}
public static void signout()
{
presence = new Presence(Presence.Type.unavailable);
// presence=new Presence(Presence.Mode.away);
connection.sendPacket(presence);
connection.disconnect();
Gtalkframe. far();

}
public Collection contact(){
LinkedList list1 = null;
Roster roster = connection.getRoster();
Collection entries = roster.getEntries();
System.out.println(roster.getEntryCount());
/*int count1 = 0;
int count2 = 0;
for(RosterEntry r:entries)
{
list1.add(r.getUser());
Presence presence1 = roster.getPresence(r.getStatus().toString());
if(presence.getType() == Presence.Type.unavailable)
{
System.out.println(list1+ “is offline”);
count1++;
}
else
{
System.out.println(list1 + “is online”);
count2++;
}

}*/
return roster.getEntries();
}

}

actually i have aproblem in roster class

41. विनीत शर्मा - September 18, 2010

Thanks to All Of You

42. विनीत शर्मा - September 18, 2010

from where i can get the documentation of such classes…..

43. Saravanan - October 28, 2010

Hi,

I am developing facebook chat client in JAVA. As we might know, FB started support XMPP earlier this year. So, I download the smack library and use to connect facebook XMPP interface. I encounter an issue on authentication part(login). With the same code, I can login to Gtalk without any problem. Have anybody tried this before? Appreciate your advice. Thanks!
Regards,
Sara

44. mayor - February 8, 2011

Hello All,

I done some reading on java socket programming, and I have also gone through the blog above. I am developing an application based on a client-server-client architecture ( C1-S1-C2). My application will be a client to a third party server and at the same time a server to different clients. My application should be able to forward request/response from it’s clients (C2) to the third party server, get response from the third-party server and forward same to the right client. I am stucked right now and don’t know how to approach this problem. Ideas will be appreciated.

Thanks,

Mayor

45. ashish - February 28, 2011

hello raza,
i have implemented the origram of your but i want to continue the chat from the other client also without disconnecting while pressing the enter..can u help plzz.i tried a lot but not working.

46. hassan - April 17, 2011

I am a non -java person and trying to write IM for my office. i am stumbling at the
step 3 : The first step is connecting to the GTalk service The code below does that ..
i made all the folder but where does the code go ? could you plz dumb it down ie where do i copy the code and how.

thanks

47. MTW - May 18, 2011

Hello , I made a java application for both client and assistant which we can call ( server ) and i wanted to communicated both client and server , actually will be like a tread in socket , multiple clients and server , and would like them to be able to exchange instant messaging through xmpp in textarea just like skype yahoo msn etc.. i’ve downloaded the smack librairy ,and i set the openfire server, but waht i dont understand is , why should i communicate with Gtalk , just i want to make my application work by itself using any type of emails , can i do that ? can you please answer me as soon as possible , and thank you again for explaing this for me its so important

48. Anonymous - July 7, 2011

how to design and develop our gtalk client application in java……..
please answer that….

49. karthick - July 7, 2011

sir, i want to develop gtalk client application, how to design and develop ? i want some idea, so please help me………

50. Mohamed Azouz - July 7, 2011

Please i want your help in
smack api
i got this exception i don’t know how to fix it

java.lang.NullPointerException
at org.jivesoftware.smackx.commands.AdHocCommandManager$4.connectionClosed(AdHocCommandManager.java:263)
at org.jivesoftware.smack.PacketReader.shutdown(PacketReader.java:134)
at org.jivesoftware.smack.XMPPConnection.shutdown(XMPPConnection.java:386)
at org.jivesoftware.smack.XMPPConnection.disconnect(XMPPConnection.java:428)
at org.jivesoftware.smack.Connection.disconnect(Connection.java:459)
at com.activedd.google.extensions.fbchat.chat.ChatProxyClient.disconnect(ChatProxyClient.java:161)
at com.activedd.google.extensions.fbchat.chat.ChatProxyClient$1.run(ChatProxyClient.java:179)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)

51. mak5283 - September 14, 2011

XMPPError connecting to talk.google.com:5222.: remote-server-error(502) XMPPError connecting to talk.google.com:5222.
— caused by: java.net.ConnectException: Connection refused: connect
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:524)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:953)
at MyGTalkClient.main(MyGTalkClient.java:27)
Nested Exception:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:28)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:512)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:953)
at MyGTalkClient.main(MyGTalkClient.java:27)
at __SHELL2.run(__SHELL2.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)

52. Anonymous - February 21, 2012

I am facing the same connection refused issue. The difference is that exception is intermittent. What could be the issue.

53. ayechanhein - April 5, 2012

i need how to make server for gtalk .please sent to me this e-mail.

54. ayechanhein - April 5, 2012

sir, i am study to program. i make gtalk .i can not do this . i need client source code . please sir .. i want to be a programmer . please help me .sir….

55. Anonymous - April 16, 2012

its very helpfull,thank’s

56. Algorithm Update Tree - April 28, 2012

Google Update Helper SEO Service Agents Picking out Methods In Panda Update 3.3

57. Anonymous - June 30, 2012

Hi, i have a IM client, using gtalk server, and i want send a message from a client (connected by me) only to another client connected by me too, not to a gtalk client (like my movil phone or gmail).
Summarizing, send messages from a couple (jid,connection) to another specific couple (jid,connection).
At the moment, conversations on my application appear in my movil phone gtalk client.
It ‘s this posible ?
I need my own XMPP server?
Thanks !!

58. Praveen - September 2, 2012

Hi Raza, need to expertise and help here. Can you please explain the following scenaro.
When i use SMACK API to connect to gtalk server using
ConnectionConfiguration connConfig = new ConnectionConfiguration(
“talk.google.com”, 5222, “gmail.com”);|
Error:
java.lang.NoClassDefFoundError: javax.net.SocketFactory is a restricted class. Please see the Google App Engine developer’s guide.
I host my app in Google app engine and tried to connect to gtalk server through the smack code in the servlet of my app. PLs help

59. Praveen - September 2, 2012

Connection is established successfully when connected from local machine, but not from the google app engine server.

60. Masarrat Siddiqui - May 14, 2013

Exception in thread “main” talk.google.com:5222 Exception: XMPPError connecting to talk.google.com:5222.; : remote-server-error(502)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:604)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1026)
at Imain.main(Imain.java:23)

61. Como criar um programa de mensagens instantâneas usando Java - Criarfazer.net - October 11, 2019

[…] Blog do Raza: como escrever seu prĂłprio cliente de mensagens instantâneas […]


Leave a reply to Harsha Cancel reply