使用smack编程(1)
连接server,并发送消息
XMPPConnection connection = new XMPPConnection("jabber.org");
connection.login("mtucker", "password");
connection.createChat("jsmith@jivesoftware.com").sendMessage("Howdy!");
开始使用smack
1、连接server
XMPPConnection conn1 = new XMPPConnection("jabber.org");
// 使用指定端口连接服务器
XMPPConnection conn2 = new XMPPConnection("jabber.org", 5222);
// 使用SSL连接
XMPPConnection connection = new SSLXMPPConnection("jabber.org");
2、使用Roster(花名册)
使用XMPPConnection.getRoster(),获得所有联系人资料
3、Packets 包(org.jivesoftware.smack.packet)
包括三种基本的packet : message, presence,IQ
例子:将你的状态改变为“外出钓鱼”
Presence presence = new Presence(Presence.Type.UNAVAILABLE);
presence.setStatus("Gone fishing");
con.sendPacket(presence);
使用Chat和GroupChat传递信息
org.jivesoftware.smack.Chat
org.jivesoftware.smack.GroupChat
1、chat
创建一个新线程发送消息
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
newChat.sendMessage("Howdy!");
使用 Chat.createMessage()方法获得一个Message,可以设定该Message的properties
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
Message newMessage = newChat.createMessage();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
使用Chat来监听回复
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
newMessage.setBody("Hi, I'm an annoying parrot-bot! Type something back to me.");
while (true) {
//netMessage 阻塞线程,直到Chat中有第二条消息
Message message = newChat.nextMessage();
newChat.sendMessage(message.getBody());
}
2、GroupChat
GroupChat newGroupChat = connection.createGroupChat("test@jivesoftware.com");
// Join the group chat using the nickname "jsmith".
newGroupChat.join("jsmith");
// Send a message to all the other people in the chat room.
newGroupChat.sendMessage("Howdy!");