Smack是一个开源,易于使用的XMPP(jabber)客户端类库。优势:简单的,功能强大,给用户发送信息只需三行代码即可完成。缺点:API并不是为大量并发用户设计,每一个客户要1个线程,占用资源大。
OpenFire是开源的、基于可拓展通信和表示协议(XMPP)、采用Java编程语言开发的实时协做服务器。 Openfire安装和使用都很是简单,并利用Web进行管理。单台服务器可支持上万并发用户。
一、首先到网址 http://www.igniterealtime.org 下载OpenFire服务器和Smack jar包
git
二、安装OpenFire登录到控制台
github
这里设置多长时间关闭闲置链接,能够判断用户是否在线的最长反应时间编程
三、建立两个测试帐号,先用Spark登录一个帐号
服务器
四、手机端登录,使用Service保持链接,并与spark端发送消息,实现双向通讯(代码和程序在后面)
网络
五、关键代码并发
配置链接OpenFire服务器,链接成功后设置响应Linstener和Receiver,这里因业务需求设置ping间隔为10s编程语言
1 public void connect() { 2 Log.i(TAG, "connect()"); 3 XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); 4 configBuilder.setHost(SmackConst.XMPP_HOST); 5 configBuilder.setServiceName(SmackConst.SERVICE_NAME); 6 configBuilder.setUsernameAndPassword(mUsername, mPassword); 7 configBuilder.setSecurityMode(SecurityMode.disabled); 8 mConnection = new XMPPTCPConnection(configBuilder.build()); 9 //Set ConnectionListener here to catch initial connect(); 10 mConnection.addConnectionListener(this); 11 try { 12 mConnection.connect(); 13 mConnection.login(); 14 if(mConnection.isAuthenticated()){//登陆成功 15 MyPingManager.setDefaultPingInterval(10);//Ping every 10 seconds 16 MyPingManager myPingManager = MyPingManager.getInstanceFor(mConnection); 17 //Set PingListener here to catch connect status 18 myPingManager.registerPingFailedListener(SmackConnection.this); 19 setupSendMessageReceiver(); 20 //Set ChatListener here to catch receive message and send NEW_MESSAGE broadcast 21 ChatManager.getInstanceFor(mConnection).addChatListener(this); 22 //Set ChatListener here to catch roster change and rebuildRoster 23 //Roster.getInstanceFor(mConnection).addRosterListener(this); 24 sendLoginBroadcast(true); 25 }else{ 26 mConnection.disconnect(); 27 Log.i(TAG, "Authentication failure"); 28 sendLoginBroadcast(false); 29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 sendLoginBroadcast(false); 33 Intent intent = new Intent(mService, mService.getClass()); 34 mService.stopService(intent); 35 } 36 37 }
自动重连TimerTask,Ping失败后启动,重连成功后关闭ide
1 private Timer reConnectTimer; 2 private int delay = 10000; 3 //pingFailed时启动重连线程 4 class ReConnectTimer extends TimerTask { 5 @Override 6 public void run() { 7 // 无网络链接时,直接返回 8 if (getNetworkState(mService) == NETWORN_NONE) { 9 Log.i(TAG, "无网络链接,"+delay/1000+"s后从新链接"); 10 reConnectTimer.schedule(new ReConnectTimer(), delay); 11 //reConnectTimer.cancel(); 12 return; 13 } 14 // 链接服务器 15 try { 16 mConnection.connect(); 17 if(!mConnection.isAuthenticated()){ 18 mConnection.login(); 19 reConnectTimer.cancel(); 20 } 21 Log.i(TAG, "重连成功"); 22 Intent intent = new Intent(SmackConst.ACTION_RECONNECT_SUCCESS); 23 mService.sendBroadcast(intent); 24 } catch (Exception e) { 25 Log.i(TAG, "重连失败,"+delay/1000+"s后从新链接"); 26 e.printStackTrace(); 27 reConnectTimer.schedule(new ReConnectTimer(), delay); 28 } 29 30 } 31 }
资源地址:https://github.com/liuhaijin/Smack-Openfire学习
菜鸟一枚,共同窗习~~测试