基于Smack3.0.4+ Openfire3.10.2下学习开发IM(二)用户分组信息(Roster、RosterGroup和RosterEntry)
以前学习过用Scoket 建立聊天,简单的建立聊天是没问题的,但如果要实现多人复杂的聊天,后台服务器代码就比较复杂,对于我这新手来讲就比较难了。后来在网上看到用openfire做服务器,利用强大的Smack API库来实现IM聊天就简单多了。
网上也有很多关于这方面的资料,我就在这里把网上的资料和自己的理解总结一下和大家一起交流学习。
需要用到以下几个工具:
Openfire 最新版本(openfire 3.10.2)
下载地址:http://www.igniterealtime.org/downloads/index.jsp
安装配置可参考:http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html
Smack 最新版本(Smack4.1.4,而我选用的Smack是3.0.4版本)
下载地址:http://www.igniterealtime.org/downloads/index.jsp
需要安装的安装好,需要下载的下载好(这里就不多作介绍)。创建项目工程,导入Smack jar包,OK,下面就一起去学习怎么实现获得 用户分组信息等一些功能!
首先第一、与服务器建立好连接
关键代码:zhou_pc为服务器IP,5222为服务器端口号
package com.openfire.util;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
public class SmackConnectionUtil {
private static XMPPConnection connection = null;
public static XMPPConnection getInstance(String serverName, int port) {
if (connection == null) {
ConnectionConfiguration config = new ConnectionConfiguration(serverName, port);
config.setSASLAuthenticationEnabled(false);
connection = new XMPPConnection(config);
}
return connection;
}
}
二、查询所有分组
通过Roster来获取所有分组,Roster可以通过connection.getRoster()来得到。
/**
* 获取所有组
*
* @param roster
* @return List<RosterGroup>
*/
public static List<RosterGroup> getGroups(Roster roster) {
List<RosterGroup> grouplist = new ArrayList<RosterGroup>();
Collection<RosterGroup> rosterGroup = roster.getGroups();
Iterator<RosterGroup> i = rosterGroup.iterator();
while (i.hasNext()) {
grouplist.add(i.next());
}
return grouplist;
}
三、返回相应(groupname)组里的所有用户(RosterEntry)
/**
* 返回相应(groupname)组里的所有用户(RosterEntry)
*
* @param roster
* @param groupName
* 组名
* @return
*/
public static List<RosterEntry> getEntriesByGroup(Roster roster,
String groupName) {
List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
RosterGroup rosterGroup = roster.getGroup(groupName);
Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();
Iterator<RosterEntry> i = rosterEntry.iterator();
while (i.hasNext()) {
Entrieslist.add(i.next());
}
return Entrieslist;
}
相关截图:
四、返回所有好友的用户信息(RosterEntry)
/**
* 返回所有好友的用户信息(RosterEntry)
*
* @param roster
* @return
*/
public static List<RosterEntry> getAllEntries(Roster roster) {
List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
Collection<RosterEntry> rosterEntry = roster.getEntries();
Iterator<RosterEntry> i = rosterEntry.iterator();
while (i.hasNext()) {
Entrieslist.add(i.next());
}
return Entrieslist;
}
源码下载地址: OpenFire3.10.2+Smack3.0.4
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。