直接上代码,都是在同一个类里边,记得换ip地址
private static ConnectionConfiguration connConfig;
private static XMPPConnection con;
//连接服务器
public static boolean openConnection(){
try {
connConfig = new ConnectionConfiguration("192.168.5.103", 5222); //5222是客户端和服务端的连接端口,其中的ip是我的内网ip
// 设置登录状态为离线
connConfig.setSendPresence(false);
con = new XMPPConnection(connConfig);
// 是否启用安全验证
connConfig.setSASLAuthenticationEnabled(false);
connConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
con.connect();
return true;
} catch (XMPPException e) {
e.printStackTrace();
}
return false;
}
//获取连接
public static XMPPConnection getConnection() {
if (con == null || !con.isConnected()) {
openConnection();
}
return con;
}
//登录
public static boolean login_conn(String account, String password) {
try {
if (connection.getConnection() == null)
return false;
/** 登录 */
connection.getConnection().login(account, password);
// 设置登录状态:在线
Presence presence = new Presence(Presence.Type.available);
connection.getConnection().sendPacket(presence);
System.out.println("登陆成功。。。");
//获取服务名
String serviceName = con.getServiceName();
//获取服务端登录用户
String user = con.getUser();
System.out.println("登录用户:"+serviceName+"||"+user);
//拉取登录用户好友
Roster roster = con.getRoster();
Collection<RosterEntry> allFri = roster.getEntries();
System.out.println("好友数量:"+roster.getEntryCount());
for(RosterEntry rosters : allFri){
String name = rosterEntry.getName();
System.out.println("好友昵称:"+name);
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
仅供学习参考