上节openfire服务器已经搭建完成,这节看看,怎么使用smack基于xmpp协议登录openfire服务器。
上节中,我们已经新建了很多用户,可以用他们来登录openfire服务端。创建服务连接类:XmppConnection.java
public class XmppConnection { public static int SERVER_PORT = 5222;//服务端口 可以在openfire上设置 public static String SERVER_HOST = "192.168.1.202";//你openfire服务器所在的ip public static String SERVER_NAME = "daihuilin";//设置openfire时的服务器名 private static XMPPConnection connection = null; private static void openConnection() { try { if (null == connection || !connection.isAuthenticated()) { XMPPConnection.DEBUG_ENABLED = true;//开启DEBUG模式 //配置连接 ConnectionConfiguration config = new ConnectionConfiguration( SERVER_HOST, SERVER_PORT, SERVER_NAME); config.setReconnectionAllowed(true); config.setSendPresence(true); config.setSASLAuthenticationEnabled(true); connection = new XMPPConnection(config); connection.connect();//连接到服务器 //配置各种Provider,如果不配置,则会无法解析数据 configureConnection(ProviderManager.getInstance()); } } catch (XMPPException xe) { xe.printStackTrace(); } } /** * 创建连接 */ public static XMPPConnection getConnection() { if (connection == null) { openConnection(); } return connection; } /** * 关闭连接 */ public static void closeConnection() { connection.disconnect(); connection = null; } /** * xmpp配置 */ private static void configureConnection(ProviderManager pm) { // Private Data Storage pm.addIQProvider("query", "jabber:iq:private",new PrivateDataManager.PrivateDataIQProvider()); // Time try { pm.addIQProvider("query", "jabber:iq:time",Class.forName("org.jivesoftware.smackx.packet.Time")); } catch (Exception e) { e.printStackTrace(); } // Roster Exchange pm.addExtensionProvider("x", "jabber:x:roster",new RosterExchangeProvider()); // Message Events pm.addExtensionProvider("x", "jabber:x:event",new MessageEventProvider()); // Chat State pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider()); pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider()); pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider()); pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider()); pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates",new ChatStateExtension.Provider()); // XHTML pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im",new XHTMLExtensionProvider()); // Group Chat Invitations pm.addExtensionProvider("x", "jabber:x:conference",new GroupChatInvitation.Provider()); // Service Discovery # Items //解析房间列表 pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",new DiscoverItemsProvider()); // Service Discovery # Info //某一个房间的信息 pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",new DiscoverInfoProvider()); // Data Forms pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider()); // MUC User pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user",new MUCUserProvider()); // MUC Admin pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin",new MUCAdminProvider()); // MUC Owner pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner",new MUCOwnerProvider()); // Delayed Delivery pm.addExtensionProvider("x", "jabber:x:delay",new DelayInformationProvider()); // Version try { pm.addIQProvider("query", "jabber:iq:version",Class.forName("org.jivesoftware.smackx.packet.Version")); } catch (ClassNotFoundException e) { // Not sure what's happening here. } // VCard pm.addIQProvider("vCard", "vcard-temp", new VCardProvider()); // Offline Message Requests pm.addIQProvider("offline", "http://jabber.org/protocol/offline",new OfflineMessageRequest.Provider()); // Offline Message Indicator pm.addExtensionProvider("offline","http://jabber.org/protocol/offline",new OfflineMessageInfo.Provider()); // Last Activity pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider()); // User Search pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider()); // SharedGroupsInfo pm.addIQProvider("sharedgroup","http://www.jivesoftware.org/protocol/sharedgroup",new SharedGroupsInfo.Provider()); // JEP-33: Extended Stanza Addressing pm.addExtensionProvider("addresses","http://jabber.org/protocol/address",new MultipleAddressesProvider()); pm.addIQProvider("si", "http://jabber.org/protocol/si",new StreamInitiationProvider()); pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",new BytestreamsProvider()); pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider()); pm.addIQProvider("command", "http://jabber.org/protocol/commands",new AdHocCommandDataProvider()); pm.addExtensionProvider("malformed-action","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.MalformedActionError()); pm.addExtensionProvider("bad-locale","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadLocaleError()); pm.addExtensionProvider("bad-payload","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadPayloadError()); pm.addExtensionProvider("bad-sessionid","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.BadSessionIDError()); pm.addExtensionProvider("session-expired","http://jabber.org/protocol/commands",new AdHocCommandDataProvider.SessionExpiredError()); } }
复制了别人的QQ登录界面,作为客户端登录界面。
我们可以先注册一个帐号,下面是注册界面:
注册代码是:
private void registered() { String accounts = mNameEt.getText().toString(); String password = mPasswdEt.getText().toString(); String email = mEmailEt.getText().toString(); String mingcheng = nameMCH.getText().toString(); Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(XmppConnection.getConnection().getServiceName()); reg.setUsername(accounts); reg.setPassword(password); reg.addAttribute("name", mingcheng); reg.addAttribute("email", email); reg.addAttribute("android", "geolo_createUser_android"); PacketFilter filter = new AndFilter(new PacketIDFilter( reg.getPacketID()), new PacketTypeFilter( IQ.class)); PacketCollector collector = XmppConnection.getConnection(). createPacketCollector(filter); XmppConnection.getConnection().sendPacket(reg); IQ result = (IQ) collector.nextResult(SmackConfiguration .getPacketReplyTimeout()); // Stop queuing results collector.cancel();// 停止请求results(是否成功的结果) if (result == null) { Toast.makeText(getApplicationContext(), "服务器没有返回结果", Toast.LENGTH_SHORT).show(); } else if (result.getType() == IQ.Type.ERROR) { if (result.getError().toString() .equalsIgnoreCase("conflict(409)")) { Toast.makeText(getApplicationContext(), "这个账号已经存在", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show(); } } else if (result.getType() == IQ.Type.RESULT) { try { XmppConnection.getConnection().login(accounts, password); Presence presence = new Presence(Presence.Type.available); XmppConnection.getConnection().sendPacket(presence); DialogFactory.ToastDialog(this, "QQ注册", "亲,恭喜你,注册成功了!"); Intent intent = new Intent(); intent.putExtra("USERID", accounts); intent.setClass(RegisterActivity.this, FriendListActivity.class); startActivity(intent); } catch (XMPPException e) { e.printStackTrace(); } } }
/** * 提交账号密码信息到服务器 */ private void submit() { String accounts = mAccounts.getText().toString(); String password = mPassword.getText().toString(); if (accounts.length() == 0 || password.length() == 0) { DialogFactory.ToastDialog(this, "登录提示", "亲!帐号或密码不能为空哦"); } else { try { //连接服务器 XmppConnection.getConnection().login(accounts, password); //连接服务器成功,更改在线状态 Presence presence = new Presence(Presence.Type.available); XmppConnection.getConnection().sendPacket(presence); //弹出登录成功提示 DialogFactory.ToastDialog(this, "登录提示", "亲,恭喜你,登录成功了!"); //跳转到好友列表 Intent intent = new Intent(); intent.putExtra("USERID", accounts); intent.setClass(LoginActivity.this, FriendListActivity.class); startActivity(intent); } catch (XMPPException e) { XmppConnection.closeConnection(); handler.sendEmptyMessage(2); } } }