How to properly listen for MultiUserChat in Smack?

2019-02-18 19:11发布

问题:

I'm not sure how to properly listen for MultiUserChats, since there are apparently two different ways to listen for them.

The first way is to add a MessageListener for each room, like this:

MultiUserChat muc = new MultiUserChat(connection,"MyGroup");
muc.addMessageListener(new PacketListener() {
    @Override
    public void processPacket(Packet packet) throws NotConnectedException {
        // TODO Auto-generated method stub
    }
});

The second way is to listen as you would for normal single-chat messages:

PacketFilter filter = new MessageTypeFilter(Message.Type.groupchat);
connection.addPacketListener(new PacketListener() {
    @Override
    public void processPacket(Packet packet) {
        Message message = (Message) packet;
        if (message.getBody() != null) {
            final String fromName = StringUtils.parseBareAddress(message.getFrom());
            final String Rtext = message.getBody();

Considering that I am also listening for file transfers, could you please help me figure out which way is the proper way?

回答1:

Since the Original Codes both Had Bugs, i used This code:

     PacketFilter messageFilter =

                new AndFilter(

                    new FromMatchesFilter(roomName+"@conference.reza-hp",true),

                    new MessageTypeFilter(Message.Type.groupchat));

            messageFilter = new AndFilter(messageFilter, new PacketFilter() {

                public boolean accept(Packet packet) {

                    Message msg = (Message) packet;

                    return msg.getBody() != null;



                }

            });

          addMessageListener(messageFilter);  
 }

    public static void addMessageListener(PacketFilter messageFilter) {

            connection.addPacketListener(new PacketListener() {

                @Override
                public void processPacket(Packet packet) throws NotConnectedException {
                     Message message = (Message)packet;  
                    String roomName = (message.getFrom().split("\\@conference.reza-
 hp"))[0];
                    String fromUser =    
 (StringUtils.parseResource(message.getFrom()).split("@\\@reza-hp"))[0];

                     System.out.println("=>"+"Room : "+roomName + "From   
 user:"+fromUser + ": "+message.getBody());  

                }
            }, messageFilter);



        }


回答2:

MultiUserChat muc = new MultiUserChat(connection,"MyGroup"); muc.addMessageListener(new PacketListener() {
    @Override
    public void processPacket(Packet packet) throws NotConnectedException {
        // TODO Auto-generated method stub
    } });

is the correct way.



标签: xmpp chat smack