2009年5月4日 星期一

google talk 監聽

測試code, 使用smack api 達成收google talk訊息的效果
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package IM;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
*
* @author 97100632
*/
public class MessageListener {
private static String username="XXXXXXXX@gmail.com";
private static String password="Password";

ConnectionConfiguration connConfig;
XMPPConnection connection;

public MessageListener()throws XMPPException{
connConfig =new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
connection =new XMPPConnection(connConfig);
connection.connect();
connection.login(username, password);

// Next, create a packet listener. We use an anonymous inner class for brevity.
PacketListener myListener = new PacketListener() {
public void processPacket(Packet packet){
Message message =(Message)packet;
System.out.println("Message From "+message.getFrom()+" : " +message.getBody() );
}
};

PacketFilter fliter =new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(myListener, fliter);


}

public void sendMessage(String to,String message){
Message msg = new Message(to, Message.Type.chat);
msg.setBody(message);
connection.sendPacket(msg);
}

public void disconnect(){
connection.disconnect();
}




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

MessageListener messageListener =new MessageListener();
/// 要傳給誰訊息
messageListener.sendMessage("Friend@gmail.com", "Hello safasgasga");


Thread.sleep(40000);

//messageListener.disconnect();

}


}

沒有留言: