Smack:当他在聊天中写消息时,是否有可能得到用户撰写的消息?

问题描述 投票:0回答:2

我们有一个聊天应用程序正在使用Smack,XMPP,ejabberd。我想知道是否有可能实现以下目标:

  1. [聊天在2个用户之间。
  2. User1正在输入一些消息。
  3. User2能够看到用户1键入的消息。

我做了一些研究,但找不到任何相关的东西。

请让我知道如何实现此用例。

提前感谢!

spring xmpp chat ejabberd smack
2个回答
0
投票

这是不可能的。您可以按用户类型发送文本,但每篇文章都将作为独立消息发送。如果您想要那个,那么您可能想拥有自己的方式。 XMPP无法这样做!


0
投票

使用Smack很容易,只要用户更改了文本,您就可以使用ChatStateExtension将键入的节发送给其他人:

 private void sendTypingStatus(final String toJid) {
     //you must have a valid xmpp connection of course
     if (null == mConnection)
        return;

    try {
        Message message = new Message(JidCreate.from(toJid));
        message.addExtension(new ChatStateExtension(ChatState.composing));

        message.setType(Message.Type.chat);
        mConnection.sendStanza(message);

    } catch (InterruptedException | SmackException.NotConnectedException | XmppStringprepException ex) {
        Log.w(TAG, "sendTypingStatus error", ex);
    }
}

另一个人应该准备好接收节并正确使用它。最好的选择是使用ChatStatesStanzaListener

public class ChatStatesStanzaListener implements StanzaListener {

private static final String TAG = ChatStatesStanzaListener.class.getSimpleName();

@Override
public void processStanza(Stanza packet) {
    Message message = (Message) packet;
    if (message.hasExtension(ChatStateExtension.NAMESPACE)) {
        ChatStateExtension chatStateExtension = (ChatStateExtension) message.getExtension(ChatStateExtension.NAMESPACE);
        ChatState chatState = chatStateExtension.getChatState();
        String fromJid = message.getFrom().asBareJid().toString();

        if (message.getType().equals(Message.Type.chat)) {
            Log.v(TAG, "got chat state " + fromJid + " " + message.getType() + " " + chatState);
 //you got youe information here, call a callback or broadcast an event, whatever

        } else if (message.getType().equals(Message.Type.groupchat)) {
            //out of your question
        }
    }
}

}

一旦建立,请不要忘记将节侦听器添加到您的xmpp连接中:1.设置节过滤器:

 // set up a stanzalistener and filter chatstates messages only
        StanzaFilter chatStatesStanzaFilter = stanza -> {
            // filter for chatstates message only
            return stanza.hasExtension(ChatStateExtension.NAMESPACE);
        };
  1. 一旦初始化xmpp连接,请使用它:

    mConnection.addAsyncStanzaListener(new ChatStatesStanzaListener(), chatStatesStanzaFilter);
    

我希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.