Smack无需聊天即可发送和接收消息

时间:2016-05-18 08:15:25

标签: java smack

我想从一个客户端向另一个客户端发送一条简单的消息,而不是打开聊天,因为永远不会有响应,所有消息都会触发相同的事件。

在smack(4.1.7)文档中,我发现可以这样做,但到目前为止我还没有找到办法。

你有什么想法怎么做吗? 使用聊天会更好(特别是根据性能:运行时和内存)吗?

1 个答案:

答案 0 :(得分:2)

对于接收你可能想要使用具有合适过滤器的同步节监听器。例如,如果你想从user@example.org接收带有正文的消息,那么你可以

XMPPConnection connection = …;
connection.addSyncStanzaListener(new StanzaListener() {

@Override
void process(Stanza stanza) {
    Message message = (Message) stanza;
    // Received new message with body from user@example.org
}, new AndFilter(MessageWithBodiesFilter.INSTANCE, 
    FromMatchesFilter.create("user@example.org")));

发送消息更加容易

Message message = new Message("user@example.org", "Hi, how are you?");
XMPPConnection connection = …;
connection.sendStanza(message);

提示:阅读Smack的源代码是了解这些内容的好方法。如果您查看source of ChatManager,您会发现我刚才写的内容。