
连接XMPP服务
private AbstractXMPPConnection getXmpptcpConnection() throws XmppStringprepException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().setXmppDomain(openfireServer)
.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled)
.setUsernameAndPassword("admin", "admin").setHost(openfireServer).setDebuggerEnabled(false).build();
AbstractXMPPConnection con = new XMPPTCPConnection(config);
xmppConnection = con;
return con;
}
注册用户
public void register(String userName,String openid) throws InterruptedException, XmppStringprepException {
HashMap<String, Object> map = new HashMap<>();
map.put("openid", openid);
List<ChatGroup> list = chatGroupService.selectByMap(map);
if (list.size() > 0)
{
return;
}
AbstractXMPPConnection con = getXmpptcpConnection();
try {
con.connect();
if (con.isConnected()) {
{
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("name", userName);
AccountManager.sensitiveOperationOverInsecureConnectionDefault(true);
Localpart usernameL = Localpart.from(userName);
AccountManager.getInstance(con).createAccount(usernameL, "123456", attributes);
}
}
} catch (SmackException | IOException | XMPPException e) {
e.printStackTrace();
} finally {
}
}
单聊发送
/**
* 单聊发消息
*
* @param receive
* @param body
* @throws Exception
*/
@RequestMapping("/sendMsg")
public void sendChatMessage(String name, String receive, String body) throws Exception {
AbstractXMPPConnection connection = ConnectionMap.get(name)
if (connection == null) {
if (name.equals("admin")) {
connection = getXmpptcpConnection("admin", "admin")
} else {
connection = getXmpptcpConnection(name, "123456")
}
// 拼凑jid
connection.connect()
if (!connection.isAuthenticated()) {
connection.login()
ConnectionMap.put(name, connection)
}
}
mChatManager = ChatManager.getInstanceFor(connection)
EntityBareJid jid = JidCreate.entityBareFrom(receive + "@" + openfireServer)
Chat chat = mChatManager.chatWith(jid)
Message message = new Message()
message.setType(Message.Type.chat)
// 发送消息格式需要处理
message.setBody(body)
chat.send(message)
}