我在 Android 上使用 asmack XMPP,但我遇到了问题。我希望播放器连接到 XMPP 服务器(仅当用户名尚未使用时),接收所有当前连接的用户并从列表中选择一个用户进行播放。
目前我正在这样登录 XMPP 服务器:
/* then connect with a newly created username */
try {
if (connection != null && connection.isConnected()) {
connection.login(username, password);
}
} catch (XMPPException e) {
Log.w("[xmpp_login] Cannot connect to XMPP server with username: " + username, "0");
e.printStackTrace();
}
我使用以下代码创建用户:
/* required attributes for creation of a new account */
HashMap<String, String> attr = new HashMap<String, String>();
attr.put("username", username);
attr.put("password", password);
manager.createAccount(username, password, attr);
} catch (XMPPException e) {
Log.w("[create_user] Cannot create new user: XMPP Exception.", "0");
Log.w(e.getMessage(), "0");
e.printStackTrace();
} catch (IllegalStateException e) {
Log.w("[create_user] Cannot create new user: not logged in.", "0");
e.printStackTrace();
}
我有两个问题:
- 如何检查用户名是否已被占用?
- 如何将所有当前连接(在线)用户的列表返回给每个玩家?由于我用谷歌搜索并没有发现任何有用的东西,我想我必须在服务器端提供该功能。这是我使用 openfire XMPP 服务器的地方。是否有我可以使用的插件 - 然后我可以从客户端调用一些函数,该函数将调用该特定插件,该插件将反过来响应所有在线玩家。
我想任何提示都会受到赞赏。谢谢
最佳答案
我找到了解决方案。要找到答案,您可以在谷歌上搜索“XMPP 共享组”。基本上我做了以下事情:
- 在 openfire XMPP 服务器中创建一个新组。
- 在用户下,确保选中“启用自动将新用户添加到组”。
当然,您必须启用正确的模块才能使这些首选项出现。
然后我们可以编写下面的函数来返回所有来自 XMPP 服务器的用户:
/*
* Return a list of #num players currently connected. (if #num == 0: return
* all players)
*/
public ArrayList<String> xmpp_playerlist(int num) {
try {
if (!connection.isConnected())
connection.connect();
if (!connection.isAuthenticated())
connection.login(user, pass);
} catch (XMPPException e) {
Log.w("Cannot connect to XMPP server with default admin username and password.", "0");
e.printStackTrace();
}
ArrayList<String> players = new ArrayList<String>();
roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
players.add(entry.getName());
}
Log.w("**Number Users: " + roster.getEntryCount(), "0");
return players;
}
关于java - asmack android XMPP - 获取所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8580657/