如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2009年9月15日星期二

Smack API Tutorial

Version: Smack 3.1.0 Beta
Smack is a Java XMPP library. You can create your own GTalk with this.
Digested from: http://www.javaprogrammingforums.com/java-tips-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html

package jabberhelloworld;

import java.util.*;
import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;
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.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class Main implements MessageListener {

XMPPConnection connection;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222, "jabber.org");
connection = new XMPPConnection(config);

connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
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());
try {
chat.sendMessage(message.getBody() + " echo");
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

public static void main(String args[]) throws XMPPException, IOException {
// declare variables
Main c = new Main();
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("yourusername", "yourpassword");

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);
}
}

没有评论: