主页 > 开发文档 > Android 基于xmpp协议,smack包,openfire服务端的高仿

Android 基于xmpp协议,smack包,openfire服务端的高仿

上节openfire服务器已经搭建完成,这节看看,怎么使用smack基于xmpp协议登录openfire服务器。

上节中,我们已经新建了很多用户,可以用他们来登录openfire服务端。创建服务连接类:XmppConnection.java

[html] view plaincopy
 
  1. public class XmppConnection {  
  2.     public static int    SERVER_PORT = 5222;//服务端口 可以在openfire上设置  
  3.     public static String SERVER_HOST = "192.168.1.202";//你openfire服务器所在的ip  
  4.     public static  String SERVER_NAME = "daihuilin";//设置openfire时的服务器名  
  5.         private static XMPPConnection connection = null;  
  6.       
  7.     private static void openConnection() {  
  8.         try {  
  9.             if (null == connection || !connection.isAuthenticated()) {  
  10.                 XMPPConnection.DEBUG_ENABLED = true;//开启DEBUG模式  
  11.                 //配置连接  
  12.                 ConnectionConfiguration config = new ConnectionConfiguration(  
  13.                         SERVER_HOST, SERVER_PORT,  
  14.                         SERVER_NAME);  
  15.                 config.setReconnectionAllowed(true);  
  16.                 config.setSendPresence(true);  
  17.                 config.setSASLAuthenticationEnabled(true);  
  18.                 connection = new XMPPConnection(config);  
  19.                 connection.connect();//连接到服务器  
  20.                 //配置各种Provider,如果不配置,则会无法解析数据  
  21.                 configureConnection(ProviderManager.getInstance());  
  22.             }  
  23.         } catch (XMPPException xe) {  
  24.             xe.printStackTrace();  
  25.         }  
  26.     }  
  27.   
  28.     /**  
  29.      * 创建连接  
  30.      */   
  31.     public static XMPPConnection getConnection() {  
  32.         if (connection == null) {  
  33.             openConnection();  
  34.         }  
  35.         return connection;  
  36.     }  
  37.       
  38.     /**  
  39.      * 关闭连接  
  40.      */   
  41.     public static void closeConnection() {  
  42.         connection.disconnect();  
  43.         connection = null;  
  44.     }  
  45.     /**  
  46.      * xmpp配置  
  47.      */  
  48.     private static void configureConnection(ProviderManager pm) {  
  49.         // Private Data Storage  
  50.         pm.addIQProvider("query", "jabber:iq:private",new PrivateDataManager.PrivateDataIQProvider());  
  51.         // Time  
  52.         try {  
  53.             pm.addIQProvider("query", "jabber:iq:time",Class.forName("org.jivesoftware.smackx.packet.Time"));  
  54.         } catch (Exception e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.         // Roster Exchange  
  58.         pm.addExtensionProvider("x", "jabber:x:roster",new RosterExchangeProvider());  
  59.         // Message Events  
  60.         pm.addExtensionProvider("x", "jabber:x:event",new MessageEventProvider());  
  61.         // Chat State  
  62.         pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider());  
  63.         pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider());  
  64.         pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider());  
  65.         pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider());  
  66.         pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider());  
  67.         // XHTML  
  68.         pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im",new XHTMLExtensionProvider());  
  69.         // Group Chat Invitations  
  70.         pm.addExtensionProvider("x", "jabber:x:conference",new GroupChatInvitation.Provider());  
  71.         // Service Discovery # Items //解析房间列表  
  72.         pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",new DiscoverItemsProvider());  
  73.         // Service Discovery # Info //某一个房间的信息  
  74.         pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",new DiscoverInfoProvider());  
  75.         // Data Forms  
  76.         pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());  
  77.         // MUC User  
  78.         pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user",new MUCUserProvider());  
  79.         // MUC Admin  
  80.         pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin",new MUCAdminProvider());  
  81.         // MUC Owner  
  82.         pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner",new MUCOwnerProvider());  
  83.         // Delayed Delivery  
  84.         pm.addExtensionProvider("x", "jabber:x:delay",new DelayInformationProvider());  
  85.         // Version  
  86.         try {  
  87.             pm.addIQProvider("query", "jabber:iq:version",Class.forName("org.jivesoftware.smackx.packet.Version"));  
  88.         } catch (ClassNotFoundException e) {  
  89.             // Not sure what's happening here.  
  90.         }  
  91.         // VCard  
  92.         pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());  
  93.         // Offline Message Requests  
  94.         pm.addIQProvider("offline", "http://jabber.org/protocol/offline",new OfflineMessageRequest.Provider());  
  95.         // Offline Message Indicator  
  96.         pm.addExtensionProvider("offline","http://jabber.org/protocol/offline",new OfflineMessageInfo.Provider());  
  97.         // Last Activity  
  98.         pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());  
  99.         // User Search  
  100.         pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());  
  101.         // SharedGroupsInfo  
  102.         pm.addIQProvider("sharedgroup","http://www.jivesoftware.org/protocol/sharedgroup",new SharedGroupsInfo.Provider());  
  103.         // JEP-33: Extended Stanza Addressing  
  104.         pm.addExtensionProvider("addresses","http://jabber.org/protocol/address",new MultipleAddressesProvider());  
  105.         pm.addIQProvider("si", "http://jabber.org/protocol/si",new StreamInitiationProvider());  
  106.         pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",new BytestreamsProvider());  
  107.         pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());  
  108.         pm.addIQProvider("command", "http://jabber.org/protocol/commands",new AdHocCommandDataProvider());  
  109.         pm.addExtensionProvider("malformed-action","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.MalformedActionError());  
  110.         pm.addExtensionProvider("bad-locale","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadLocaleError());  
  111.         pm.addExtensionProvider("bad-payload","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadPayloadError());  
  112.         pm.addExtensionProvider("bad-sessionid","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadSessionIDError());  
  113.         pm.addExtensionProvider("session-expired","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.SessionExpiredError());  
  114.     }  
  115. }  

复制了别人的QQ登录界面,作为客户端登录界面。

我们可以先注册一个帐号,下面是注册界面:

注册代码是:

 

[html] view plaincopy
 
  1. private void registered() {  
  2.   
  3.         String accounts = mNameEt.getText().toString();  
  4.         String password = mPasswdEt.getText().toString();  
  5.         String email = mEmailEt.getText().toString();  
  6.         String mingcheng = nameMCH.getText().toString();  
  7.           
  8.           
  9.         Registration reg = new Registration();  
  10.         reg.setType(IQ.Type.SET);  
  11.         reg.setTo(XmppConnection.getConnection().getServiceName());  
  12.         reg.setUsername(accounts);  
  13.         reg.setPassword(password);  
  14.         reg.addAttribute("name", mingcheng);  
  15.         reg.addAttribute("email", email);  
  16.           
  17.         reg.addAttribute("android", "geolo_createUser_android");  
  18.         PacketFilter filter = new AndFilter(new PacketIDFilter(  
  19.                                         reg.getPacketID()), new PacketTypeFilter(  
  20.                                         IQ.class));  
  21.         PacketCollector collector = XmppConnection.getConnection().  
  22.         createPacketCollector(filter);  
  23.         XmppConnection.getConnection().sendPacket(reg);  
  24.         IQ result = (IQ) collector.nextResult(SmackConfiguration  
  25.                                         .getPacketReplyTimeout());  
  26.                                 // Stop queuing results  
  27.         collector.cancel();// 停止请求results(是否成功的结果)  
  28.         if (result == null) {  
  29.         Toast.makeText(getApplicationContext(), "服务器没有返回结果", Toast.LENGTH_SHORT).show();  
  30.         } else if (result.getType() == IQ.Type.ERROR) {  
  31.         if (result.getError().toString()  
  32.                                 .equalsIgnoreCase("conflict(409)")) {  
  33.             Toast.makeText(getApplicationContext(), "这个账号已经存在", Toast.LENGTH_SHORT).show();  
  34.             } else {  
  35.                 Toast.makeText(getApplicationContext(), "注册失败",  
  36.                                                 Toast.LENGTH_SHORT).show();  
  37.             }  
  38.         } else if (result.getType() == IQ.Type.RESULT) {  
  39.             try {  
  40.                 XmppConnection.getConnection().login(accounts, password);  
  41.                 Presence presence = new Presence(Presence.Type.available);  
  42.                 XmppConnection.getConnection().sendPacket(presence);  
  43.                 DialogFactory.ToastDialog(this, "QQ注册", "亲,恭喜你,注册成功了!");  
  44.                 Intent intent = new Intent();  
  45.                 intent.putExtra("USERID", accounts);  
  46.                 intent.setClass(RegisterActivity.this, FriendListActivity.class);  
  47.                 startActivity(intent);  
  48.             } catch (XMPPException e) {  
  49.                 e.printStackTrace();  
  50.             }     
  51.         }  
  52.           
  53.     }  

接着就可以登录了,下面的是登录代码:

 

 

[html] view plaincopy
 
  1. /**  
  2.      * 提交账号密码信息到服务器  
  3.      */  
  4.     private void submit() {  
  5.         String accounts = mAccounts.getText().toString();  
  6.         String password = mPassword.getText().toString();  
  7.         if (accounts.length() == 0 || password.length() == 0) {  
  8.             DialogFactory.ToastDialog(this, "登录提示", "亲!帐号或密码不能为空哦");  
  9.         } else {  
  10.             try {  
  11.                 //连接服务器  
  12.                 XmppConnection.getConnection().login(accounts, password);  
  13.                 //连接服务器成功,更改在线状态  
  14.                 Presence presence = new Presence(Presence.Type.available);  
  15.                 XmppConnection.getConnection().sendPacket(presence);  
  16.                 //弹出登录成功提示  
  17.                 DialogFactory.ToastDialog(this, "登录提示", "亲,恭喜你,登录成功了!");  
  18.                 //跳转到好友列表  
  19.                 Intent intent = new Intent();  
  20.                 intent.putExtra("USERID", accounts);  
  21.                 intent.setClass(LoginActivity.this, FriendListActivity.class);  
  22.                 startActivity(intent);  
  23.             } catch (XMPPException e) {  
  24.                 XmppConnection.closeConnection();  
  25.                 handler.sendEmptyMessage(2);  
  26.             }             
  27.         }  
  28.     }  

 已同步至 yuanqihesheng的微博