Thursday, September 22, 2011

Java - GTalk Client using SMACK XMPP API



/*GtalkClient.java*/


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;
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;


/**
 *
 * @author dhanoopbhaskar
 */
public class GtalkClient implements Runnable, MessageListener {
   
    ConnectionConfiguration connConfig = null;
    XMPPConnection xMPPConnection = null;
    BufferedReader readFromKeyboard = null;
    String toAddresss = null;
    String[] buddies = null;
    int buddySize = 0;


    public GtalkClient() {
        /**
         * Set the 'ConnectionConfiguration' with
         * -host name
         * -port number
         * -service name
         */
        connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
        /**
         * Create an instance of 'XMPPConnection' with the already created
         * instance of 'ConnectionConfiguration'
         */
        xMPPConnection = new XMPPConnection(connConfig);      
        try {
            /**
             * Connecting to the service
             */
            xMPPConnection.connect();
            /**
             * Login to the GMail account from which you want to chat
             * Provide
             * -email id
             * -password
             */
            xMPPConnection.login("user-name@gmail.com", "password");
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
        /**
         * BufferedReader to read from the keyboard
         */
        readFromKeyboard = new BufferedReader(new InputStreamReader(System.in));
       
        displayBuddyList();
       
        System.out.println("\n\nEnter the recipient's Email Id! or "
                + "buddy id in the list");
        try {
            String temp = readFromKeyboard.readLine();
            try {
                int j = Integer.parseInt(temp);
                toAddresss = getBuddy(j);
                System.out.println("Buddy <" + toAddresss + "> selected!");
            } catch(NumberFormatException exp) {
                toAddresss = temp;
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
       
       
        System.out.println("Enter your chat messages one by one!");
        System.out.println("[Enter \"quit\" to end the chat!]");
       
        String msg = "";
        while(true) {
            try {
                msg = readFromKeyboard.readLine();
            } catch (IOException ex) {
                System.out.println("Error: " + ex.getMessage());
            }
           
            if(msg.equalsIgnoreCase("quit")) {
                System.out.println("--Chat Ended--");
                break;
            } else {
                sendMessage(toAddresss, msg);
            }
        }
    }


    /**
     *
     * @param recipient
     * @param message
     */
    private void sendMessage(String recipient, String message) {
        /**
         * Create an instance of 'Chat' providing the recipient's email-id
         * and an instance of MessageListener interface(The predefined
         * reference 'this' will do, since the class
         * implements the MessageListener interface.        
         */
        Chat chat = xMPPConnection.getChatManager().createChat(recipient, this);
        try {
            /**
             * Sending the chat message
             */
            chat.sendMessage(message);
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
    }
    

      /**
       * This method belongs to MessageListener interface.
       * It listens for the incoming chat messages.
       */
    @Override

    public void processMessage(Chat chat, Message msg) {       
        String msgStr = msg.getBody();
        System.out.println("<" + chat.getParticipant() + ">  says " + msgStr);
    }
   
    public static void main(String[] args) {
        GtalkClient gtalkClient = new GtalkClient();      
    }


    @Override
    public void run() {      
    }
   
    private void displayBuddyList() {
        Roster roster = xMPPConnection.getRoster();
        Collection entries = roster.getEntries();


        System.out.println("\n\n------------Your Buddies!!------------");
        System.out.println(entries.size() + " buddy(ies):\n");
        Iterator iter = entries.iterator();
        buddySize = entries.size();  
        buddies = new String[buddySize];
        int i = 0;
        while (iter.hasNext()) {
            RosterEntry rosterEntry = (RosterEntry) iter.next();
            buddies[i] = rosterEntry.getUser();
            i++;
            System.out.println(i + ". " + rosterEntry.getUser());          
        }
        System.out.println("--------------------------------------");
    }
   
    private String getBuddy(int i) {
        String buddy = "";
        if(i > 0 && i <= buddySize) {
            buddy = buddies[i-1];
        } else {
            System.out.println("Invalid Buddy Id!! Selected default one!!");
            buddy = buddies[0];
        }
        return buddy;
    }
}





------Sample Output------





------------Your Buddies!!------------
3 buddy(ies):

1. dhanoopbhaskar@gmail.com
2. dhanoopbhaskar4@gmail.com
3. dhanoopbhaskar3@gmail.com
--------------------------------------


Enter the recipient's Email Id! or buddy id in the list
1
Buddy <dhanoopbhaskar@gmail.com> selected!
Enter your chat messages one by one!
[Enter "quit" to end the chat!]
hi
<dhanoopbhaskar@gmail.com> says hello
quit
--Chat Ended--





NB: To run and test the above program you need to download Smack XMPP API from here ... 



0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...