我使用下面的代码发送消息。
// Assume we've created an XMPPConnection name "connection".
ChatManager chatmanager = connection.getChatManager();
Chat newChat = chatmanager.createChat("jsmith@jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
下面用于异步接收发送到我的 JabberID 的消息。
// Create a packet filter to listen for new messages from a particular
// user. We use an AndFilter to combine two other filters.
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class),
new FromContainsFilter("mary@jivesoftware.com"));
// Assume we've created an XMPPConnection name "connection".
// First, register a packet collector using the filter we created.
PacketCollector myCollector = connection.createPacketCollector(filter);
// Normally, you'd do something with the collector, like wait for new packets.
// Next, create a packet listener. We use an anonymous inner class for brevity.
PacketListener myListener = new PacketListener() {
public void processPacket(Packet packet) {
// Do something with the incoming packet here.
}
};
// Register the listener.
connection.addPacketListener(myListener, filter);
发消息没问题。
但是,在我向该 JabberID 发送消息之前,无法接收来自另一个 JabberID 的消息。
之后,我会正确收到它发送的消息。
请注意,我经常需要从不在我的列表中的 jabberID 接收消息,而且我的应用程序通常不是开始聊天的一方。
上面的代码是 smack 示例,但我的代码完全一样,只是我没有创建 PacketListener 内联实现。