想象中如此简单的功能,想不到却这般大费周折。
如要实现,必须先确保:
1. openfire中安装有“Presence” 插件。
![点击查看原始大小图片 openfire xmpp 如何判断用户是否在线 - Mr.7 - Mr.7](http://img169.ph.126.net/8Mgwvjl6bi66ocmJRTdPxg==/1456070054525824785.jpg)
2. 确保该插件设置可允许任何人访问(如果是跨域浏览的话)
![点击查看原始大小图片 openfire xmpp 如何判断用户是否在线 - Mr.7 - Mr.7](http://img618.ph.126.net/pCS0TqBHzbB5aEmDJL28qw==/1963006487581684530.jpg)
然后通过如下方式访问:http://www.igniterealtime.org/projects/openfire/plugins/presence/readme.html 。
访问结果如下:
账号 | 状态 | xml | text |
user1 | 不存在 | <presence type="error" from="user1@my.openfire.com"><error code="403" type="auth"><forbidden xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></presence> | null |
user2 | 离线 | <presence type="unavailable" from="user2@my.openfire.com"><status>Unavailable</status></presence> | Unavailable |
user8 | 在线 | <presence from="user8@my.openfire.com/trm"><priority>0</priority></presence> 或者 <presence id="6Mgiu-13" from="user8@my.openfire.com/Smack"/> | null |
java代码:
import java.net.*;
import java.io.*;
/**
* 判断openfire用户的状态
* strUrl : url格式 - http://my.openfire.com:9090/plugins/presence/status?jid=user1@my.openfire.com&type=xml
* 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线
* 说明 :必须要求 openfire加载 presence 插件,同时设置任何人都可以访问
*/
public static short IsUserOnLine(String strUrl)
{
short shOnLineState = 0; //-不存在-
try
{
URL oUrl = new URL(strUrl);
URLConnection oConn = oUrl.openConnection();
if(oConn!=null)
{
BufferedReader oIn = new BufferedReader(new InputStreamReader(oConn.getInputStream()));
if(null!=oIn)
{
String strFlag = oIn.readLine();
oIn.close();
if(strFlag.indexOf("type=\"unavailable\"")>=0)
{
shOnLineState = 2;
}
if(strFlag.indexOf("type=\"error\"")>=0)
{
shOnLineState = 0;
}
else if(strFlag.indexOf("priority")>=0 || strFlag.indexOf("id=\"")>=0)
{
shOnLineState = 1;
}
}
}
}
catch(Exception e)
{
}
return shOnLineState;
}
转自:http://iammr.7.blog.163.com/blog/static/491026992010101635939962/
虽然接触了openfire有段时间了,但还是没有深入去理解其原理,所以,遇到一些新问题就有点束手无策,今天又遇到一个,开始以为用户的在线状态会存数据库里面呢,没想到openfire没这么干,存在了session里面,找了很多资料,终于找到了方法,好像也还很简单的。废话不多说,进入正题:
首先我们要确保openfire 服务器中安装了presence 插件,同时在openfire后台中的服务器设置中进入Presence Service处,设置任何人都可以访问的权限(不过这样设置的话会对安全性有一定影响)。
然后就是代码判断了:
//传入路径格式: String url = "http://localhost:9090/plugins/presence/status?jid=admin@meson.com&type=xml";
public static int IsUserOnLine(String strUrl) {
int state = 0;
//返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线
try {
URL oUrl = new URL(strUrl);
URLConnection oConn = oUrl.openConnection();
if (oConn != null) {
BufferedReader oIn = new BufferedReader(new InputStreamReader(oConn.getInputStream()));
if (null != oIn) {
String strFlag = oIn.readLine();
//System.out.println(strFlag);
oIn.close();
if (strFlag.indexOf("type=\"unavailable\"") >= 0) {
state = 2;
}
if (strFlag.indexOf("type=\"error\"") >= 0) {
state = 0;
} else if (strFlag.indexOf("priority") >= 0 || strFlag.indexOf("id=\"") >= 0) {
state = 1;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return state;
} //这是网上copy的代码
到这里问题就算解决了,不过对于openfire,还有很多未知数等着解决....