如何使用Smack在Android XMPP多用户聊天中创建和加入组

时间:2017-03-20 12:25:26

标签: android xmpp smack multiuserchat

我正在尝试为我的应用程序进行多用户聊天。我已经完成了单用户通信的编码,它工作正常。我无法在多用户聊天中创建或加入群组。以下是我的代码。

public class MyXMPP {

public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serviceName = "", hostAddress = "";
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
XmppService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
private static ChatHandler chatHandler;
private MultiUserChat mMultiUserChat;
private MultiUserChatManager manager;

public String roomName = "new";
public String serverName = "conference.";

public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
    this.serviceName = mServiceName;
    this.hostAddress = mHostAddress;
    this.loginUser = loginUser;
    this.passwordUser = passwordUser;
    this.context = context;
    init();
}

public static MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {
    if (instance == null) {
        instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
        instanceCreated = true;
    }
    return instance;

}

public org.jivesoftware.smack.chat.Chat Mychat;

ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;

String text = "";
String mMessage = "", mReceiver = "";

static {
    try {
        Class.forName("org.jivesoftware.smack.ReconnectionManager");
    } catch (ClassNotFoundException ex) {
        // problem loading reconnection manager
    }
}

public void init() {
    mMessageListener = new MMessageListener(context);
    mChatManagerListener = new ChatManagerListenerImpl();
    initialiseConnection();
}

private void initialiseConnection() {

    XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
    config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    config.setServiceName(serviceName);
    config.setHost(hostAddress);
    config.setDebuggerEnabled(true);
    XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
    XMPPTCPConnection.setUseStreamManagementDefault(true);
    connection = new XMPPTCPConnection(config.build());
    XMPPConnectionListener connectionListener = new XMPPConnectionListener();
    connection.addConnectionListener(connectionListener);

}

public void disconnect() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            connection.disconnect();
        }
    }).start();
}

public void connect(final String caller) {

    AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected synchronized Boolean doInBackground(Void... arg0) {
            if (connection.isConnected())
                return false;
            isconnecting = true;
            if (isToasted)
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {

                        Toast.makeText(context,
                                caller + "=>connecting....",
                                Toast.LENGTH_LONG).show();
                    }
                });
            Log.d("Connect() Function", caller + "=>connecting....");

            try {

                connection.connect();

                ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
                reconnectionManager.setEnabledPerDefault(false);
                reconnectionManager.enableAutomaticReconnection();

                DeliveryReceiptManager dm = DeliveryReceiptManager
                        .getInstanceFor(connection);
                dm.setAutoReceiptMode(AutoReceiptMode.always);
                dm.addReceiptReceivedListener(new ReceiptReceivedListener() {

                    @Override
                    public void onReceiptReceived(final String fromid,
                                                  final String toid, final String msgid,
                                                  final Stanza packet) {

                    }
                });

                connected = true;

            } catch (IOException e) {
                Log.e("(" + caller + ")", "IOException: " + e.getMessage());
            } catch (SmackException e) {
                Log.e("(" + caller + ")",
                        "SMACKException: " + e.getMessage());
            } catch (XMPPException e) {
                Log.e("connect(" + caller + ")",
                        "XMPPException: " + e.getMessage());

            }
            return isconnecting = false;
        }
    };
    connectionThread.execute();
}

public void login() {

    try {

        connection.login(loginUser, passwordUser);
        Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");


                // Call to create Multi User Chat Group
                join();    

    } catch (XMPPException | SmackException | IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private class ChatManagerListenerImpl implements ChatManagerListener {
    @Override
    public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
                            final boolean createdLocally) {
        if (!createdLocally)
            chat.addMessageListener(mMessageListener);

    }

}


public int sendMessage(String senderID, String mMessage) {

    if (!chat_created) {
        Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
        chat_created = true;
    }
    final Message message = new Message();
    message.setBody(mMessage);
    message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
    message.setType(Message.Type.chat);
    try {
        if (connection.isAuthenticated()) {
            Mychat.sendMessage(message);
            return 1;
        } else {
            login();
            return 0;
        }
    } catch (SmackException.NotConnectedException e) {

        Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
        return 0;

    } catch (Exception e) {

        Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
        return 0;
    }

}

public class XMPPConnectionListener implements ConnectionListener {
    @Override
    public void connected(final XMPPConnection connection) {

        Log.d("xmpp", "Connected!");
        connected = true;
        if (!connection.isAuthenticated()) {
            login();
        }
    }

    @Override
    public void connectionClosed() {
        if (isToasted)

            Log.d("xmpp", "ConnectionCLosed!");

        System.out.println("-------------ConnectionCLosed!----------------");
        instance = null;
        connected = false;
        chat_created = false;
        loggedin = false;
    }

    @Override
    public void connectionClosedOnError(Exception arg0) {

        Log.d("xmpp", "ConnectionClosedOn Error!");
        connected = false;
        instance = null;
        chat_created = false;
        loggedin = false;
    }

    @Override
    public void reconnectingIn(int arg0) {

        Log.d("xmpp", "Reconnectingin " + arg0);

        System.out.println("----------prem Reconnectingin----------------" + arg0);

        loggedin = false;
    }

    @Override
    public void reconnectionFailed(Exception arg0) {

        Log.d("xmpp", "ReconnectionFailed!");
        connected = false;
        instance = null;
        chat_created = false;
        loggedin = false;
    }

    @Override
    public void reconnectionSuccessful() {

        Log.d("xmpp", "ReconnectionSuccessful");
        connected = true;

        chat_created = false;
        loggedin = false;
    }

    @Override
    public void authenticated(XMPPConnection arg0, boolean arg1) {
        Log.d("xmpp", "Authenticated!");
        loggedin = true;

        ChatManager.getInstanceFor(connection).addChatListener(
                mChatManagerListener);

        chat_created = false;
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();

    }
}

private class MMessageListener implements ChatMessageListener {

    public MMessageListener(Context contxt) {
    }

    @Override
    public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
                               final Message message) {
        Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
                + message);

        if (message.getType() == Message.Type.chat
                && message.getBody() != null) {
            System.out.println("-----------xmpp message-------------" + message.getBody());

            // Here I am receiving messages which would be handled later
        }
    }

}


public boolean join(){
  try {
        MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
        MultiUserChat multiUserChat = multiUserChatManager.getMultiUserChat(roomName + "@" + serverName + ServiceConstant.XMPP_HOST_URL);
        multiUserChat.addMessageListener(new MessageListener() {
            @Override
            public void processMessage(Message message) {
                Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
                        + message);


            }
        });

       // Getting Error at the below line. 
       multiUserChat.createOrJoin(loginUser);

      return true;


    }catch (Exception e){
        e.printStackTrace();
    }

    return false;
}

}

在调用 join()函数时尝试执行上述代码时出现XMPP错误。

错误 multiUserChat.createOrJoin(loginUser)这个地方。

  

XMPPError:remote-server-not-found - 取消at   org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:220)       在org.jivesoftware.smackx.muc.MultiUserChat.enter(MultiUserChat.java:311)       在org.jivesoftware.smackx.muc.MultiUserChat.createOrJoin(MultiUserChat.java:400)       在org.jivesoftware.smackx.muc.MultiUserChat.createOrJoin(MultiUserChat.java:376)

请帮帮我。在此先感谢。

3 个答案:

答案 0 :(得分:0)

我认为您在创建多用户聊天(getMultiUserChat)时没有正确传递jabber ID。创建jid的方式是roomName @ conferenceServername / resourceId。您需要检查在创建JID时需要附加的会议服务器名称应该是什么。这可以通过检查服务器端的配置或使用item discovery feature来完成,如果会议被用作XMPP端的单独组件。

答案 1 :(得分:0)

对于群聊,您需要预先设置“会议”。与service_url。

示例代码:

final MultiUserChatManager multiUserChatManager = 
             MultiUserChatManager.getInstanceFor(abstractXMPPConnection);
final MultiUserChat multiUserChat = 
             multiUserChatManager.getMultiUserChat(
             JidCreate.entityBareFrom(groupChatRoomName + 
                          "@conference." + SERVICE_URL));
multiUserChat.create(Resourcepart.from((groupChatRoomName))
               .getConfigFormManager()
               .submitConfigurationForm();

答案 2 :(得分:0)

  • 创建房间并将成员添加到房间示例:请参考joinChatRoom(String userName,String roomName)函数来创建和加入房间。

    http://keepnote.cc/MUCGroupCreation