单聊发送消息
Connection connection = new XMPPConnection("服务器IP");
connection.connect();
connection.login("mtucker", "password");//登录
Chat chat = connection.getChatManager().createChat("[email protected]", new MessageListener() {
public void processMessage(Chat chat, Message message) {//接收消息
System.out.println("Received message: " + message);
}
});
chat.sendMessage("Howdy!");//发送消息
连接与注销
// 为新的连接创建一个配置
ConnectionConfiguration config = new ConnectionConfiguration("服务器IP", 5222);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
Connection connection = new XMPPConnection(config);
// 连接到服务器
connection.connect();
// 登录到服务器
connection.login("username", "password", "SomeResource");
....
// 从服务器上注销
connection.disconnect();
群聊
/**
* 创建一个群聊室
*/
public static void createMutiUserChat(Connection con) throws XMPPException {
//创建一个多人聊天类,这个类的第二个参数规则必须是[房间名称@组聊天服务名.服务器名称]
//这个组聊天服务名可以在服务器[分组聊天-分组聊天设置]中看到
MultiUserChat muc = new MultiUserChat(con, "[email protected]");
// 这个create后面的参数是你在群聊里的名称
muc.create("testbot");
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
// 设置默认的房间参数,如果不需要可以自己改动
submitForm.setDefaultAnswer(field.getVariable());
System.out.println(field.getLabel()+ ":" +field.getVariable());
}
}
// 设置房间的拥有者
List<String> owners = new ArrayList<String>();
owners.add("haojiang@"+SERVICE_NAME);
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
submitForm.setAnswer("muc#roomconfig_roomname", "唐吉诃德");
// 发送房间的配置
muc.sendConfigurationForm(submitForm);
}
群聊室的属性
房间名称:muc#roomconfig_roomname
描述:muc#roomconfig_roomdesc
允许占有者更改主题:muc#roomconfig_changesubject
最大房间占有者人数:muc#roomconfig_maxusers
其 Presence 是 Broadcast 的角色:muc#roomconfig_presencebroadcast
列出目录中的房间:muc#roomconfig_publicroom
房间是持久的:muc#roomconfig_persistentroom
房间是适度的:muc#roomconfig_moderatedroom
房间仅对成员开放:muc#roomconfig_membersonly
允许占有者邀请其他人:muc#roomconfig_allowinvites
需要密码才能进入房间:muc#roomconfig_passwordprotectedroom
密码:muc#roomconfig_roomsecret
能够发现占有者真实 JID 的角色:muc#roomconfig_whois
登录房间对话:muc#roomconfig_enablelogging
仅允许注册的昵称登录:x-muc#roomconfig_reservednick
允许使用者修改昵称:x-muc#roomconfig_canchangenick
允许用户注册房间:x-muc#roomconfig_registration
房间管理员:muc#roomconfig_roomadmins
房间拥有者:muc#roomconfig_roomowners