一、相关知识背景介绍
1. IM(InstantMessaging),即实时通讯,这是一种类似与QQ、微信等的通讯方式。
2.Smack 是一个开源的,易于使用的XMPP客户端类库,是使用java编写的,也是Spark软件的的核心技术。
3.openfire采用java开发,开源的实时协作服务器基于XMPP协议。Openfire的安装和使用非常简单,并且有自己的Web管理平台。
4.要进行这样的集成开发,我们需要准备的就是安装好Openfire服务器,然后根据需要使用Smack类库编写我们需要的客户端程序。
5.本次开发使用 Smack 4.1+ 版本
二、环境搭建
Openfire的下载和安装
官方下载地址 : http://www.igniterealtime.org/downloads/index.jsp
安装和配置 : http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.htmlSmack 类库的选择
这是我引用的Smack类库:
准备好这些,我们就要开始使用Smack API 进行IM编程了。
我将Smack代码放进线程中,重要的步骤会有注释,具体步骤和实现如下,
new Thread(new Runnable() {
@Override
public void run() {
try {
/**1.配置相關參數*/
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(userName, password).setServiceName(serviceName).setHost(host)
.setPort(servicePort).setSecurityMode(SecurityMode.disabled).build();
final AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
/**2.建立連接*/
conn2.connect();
conn2.login("userName", "password");// 登錄賬號和密碼
ChatManager chatmanager = ChatManager.getInstanceFor(conn2);
/** 3.添加消息監聽器,獲取消息 */
chatmanager.addChatListener(new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
@Override
public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat || message.getType() == Message.Type.normal) {
if (message.getBody() != null) {
/**回復消息的格式*/
System.out.println(message.getFrom() + " : " + message.getBody());
}
}
}
});
}
});
/**4.建立会话*/
Chat newChat = chatmanager.createChat(toJid);
/** 用戶輸入 */
Scanner input = new Scanner(System.in);
while (true) {
String message = input.nextLine();
newChat.sendMessage(message);
}
} catch (SmackException e) {
System.out.println("SmackException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} catch (XMPPException e) {
System.out.println("XMPPEXception");
e.printStackTrace();
}
}
}).start();
实现效果展示:
参考博文
http://blog.youkuaiyun.com/qinnimei/article/details/50469087
http://blog.youkuaiyun.com/shimiso/article/details/8816540
http://www.eoeandroid.com/forum.php?