Search code examples
javasmack

Smack send and receive message without chat


I would like to send a simple message from one client to another one not opening a chat because there will never be a response and all messages fire the same event.

In the smack (4.1.7) documentation I found out that it is possible to do so but so far I did not find a way how to do it.

Do you have any ideas how to do it? Would it be better (especially acording to performance: runtime and memory) to use the chat?


Solution

  • For receiving you'd probably want to use a synchronous stanza listener with a suitable filter.For example, if you want to receive messages with a body from user@example.org, then you could

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

    Sending messages is even easier

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

    Hint: Reading the source code of Smack is a great way to learn about such stuff. If you look at the source of ChatManager, you will find what I've just written above.