Using google talk from java example

Sending and receiving messages to and from google talk accounts is actually very easy. Google uses the xmpp (jabber) protocol. The Smack library enables you to use the xmpp protocol in java.

I was actually trying to use xmpp in apache camel, but couldn’t get it working with google accounts, just with other accounts, so i decided to do some basic smack testing. Smack doesn’t have any problems with google accounts. Here’s a basic example i wrote to test it

// connect to gtalk server
ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
XMPPConnection connection = new XMPPConnection(connConfig);
connection.connect();

// login with username and password
connection.login("camel.test.1", "secret");

// set presence status info
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);

// send a message to somebody
Message msg = new Message("[email protected]", Message.Type.chat);
msg.setBody("hello");
connection.sendPacket(msg);

// receive msg
PacketListener pl = new PacketListener() {
  @Override
  public void processPacket(Packet p) {
    System.out.println(p.getFrom() + ": " + p.toString());
    if (p instanceof Message) {
      Message msg = (Message) p;
      System.out.println(msg.getFrom() + ": " + msg.getBody());
    }
  }
};
connection.addPacketListener(pl, null);

// wait for user to end program
System.in.read();

// set presence status to unavailable
presence = new Presence(Presence.Type.unavailable);
connection.sendPacket(presence);

This is a very basic example, you’d normally create a chat session, and listen for messages part of the chat. More info on the smack site.

blog comments powered by Disqus