public boolean openConnection() { new AndroidSmackInitializer().initialize(); try { if (null == connection || !connection.isAuthenticated()) { // XMPPConnection.DEBUG_ENABLED = true;// ����DEBUGģʽ // �������� XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder(); builder.setHost(SERVER_HOST); builder.setServiceName(SERVER_NAME); builder.setPort(SERVER_PORT); builder.setSendPresence(true); builder.setCompressionEnabled(false); builder.setSecurityMode(SecurityMode.disabled); XMPPTCPConnectionConfiguration config = builder.build(); connection = new XMPPTCPConnection(config); try { connection.connect(); } catch (SmackException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ���ӵ������� // ���ø���Provider��������ã������������� configureConnection(new ProviderManager()); return true; } } catch (XMPPException xe) { xe.printStackTrace(); connection = null; } return false; }
@OnClose public void onClose(Session session) { System.out.println(session.getId() + "------has closed"); // sess_map.remove(session.getId()); AbstractXMPPConnection conn = conn_map.get(session.getId()); conn.disconnect(); sess_map.remove(session.getId()); conn_map.remove(session.getId()); }
public static void main(String[] args) { SmackConfiguration.DEBUG = true; SmackConfiguration.setDefaultPacketReplyTimeout(10 * 1000); XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); configBuilder.setUsernameAndPassword("registeruser2", "123456"); configBuilder.setServiceName("ejabberddemo.com"); configBuilder.setDebuggerEnabled(true).build(); // 必须在用户状态为离线状态 configBuilder.setSendPresence(false); AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build()); try { connection.connect(); } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XMPPException e) { e.printStackTrace(); } // FIXME OfflineMessageManager offlineManager = new OfflineMessageManager(connection); try { connection.login(); } catch (XMPPException e) { e.printStackTrace(); } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { System.out.println(offlineManager.supportsFlexibleRetrieval()); System.out.println(offlineManager.getMessageCount()); } catch (SmackException.NoResponseException e) { e.printStackTrace(); } catch (XMPPException.XMPPErrorException e) { e.printStackTrace(); } catch (SmackException.NotConnectedException e) { e.printStackTrace(); } // 上线 Presence presence = new Presence(Presence.Type.available); try { connection.sendPacket(presence); } catch (SmackException.NotConnectedException e) { e.printStackTrace(); } }
/** �ر����� */ public void closeConnection() { if (connection != null) { // �Ƴ��B�ӱO // connection.removeConnectionListener(connectionListener); if (connection.isConnected()) connection.disconnect(); connection = null; } Log.i("XmppConnection", "�P�]�B��"); }
@Override public void logoutAndDisconnect() { if (connection != null) { LOGGER.info("Destroying connection..."); connection.disconnect(); connection = null; } }
/* * (non-Javadoc) * * @see * com.bearmaster.talk.services.impl.ChatService#login(java.lang.String, * java.lang.String) */ @Override public void login(String username, String password) throws TalkException { if (connection != null) { try { if (!connection.isConnected()) { LOGGER.debug("Connecting..."); connection.connect(); } LOGGER.debug("Attemtping login..."); connection.login(username, password); LOGGER.debug("Login completed."); Presence presence = new Presence(Presence.Type.available); presence.setMode(Presence.Mode.available); connection.sendStanza(presence); LOGGER.debug("Presence set to available"); } catch (SmackException | IOException | XMPPException e) { throw new TalkException("Error during login", e); } } else { throw new IllegalStateException(ERROR_CONNECTION_IS_NOT_INITIALISED); } }
public static void main(String[] args) { String username = "******", password = "******", resource = "viewt", serviceName = "openfire-test", host = "192.168.1.117"; host = "127.0.0.1"; XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() // .setUsernameAndPassword(username, password) .setServiceName(serviceName) .setHost(host) .setPort(5222) // .setDebuggerEnabled(true) .setSecurityMode(SecurityMode.disabled) .build(); // AbstractXMPPConnection conn2 = new XMPPTCPConnection(username,password,"127.0.0.1"); AbstractXMPPConnection conn2 = new XMPPTCPConnection(config); try { // SASLAuthentication.registerSASLMechanism(new SASLPlainMechanism()); conn2.connect(); // conn2.login(); conn2.login(username, password, resource); final Roster roster = Roster.getInstanceFor(conn2); Set<RosterEntry> set = roster.getEntries(); Iterator<RosterEntry> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().getName()); } // roster.createGroup("family"); // roster.createEntry("elijah@openfire-test", "elijah", new String[]{"family"}); roster.setSubscriptionMode(Roster.SubscriptionMode.reject_all); // roster. roster.addRosterListener( new RosterListener() { public void presenceChanged(Presence presence) { System.out.println("Presence changed: " + presence.getFrom() + " " + presence); } public void entriesUpdated(Collection<String> addresses) { System.out.println("Presence changed: entriesUpdated"); } public void entriesDeleted(Collection<String> addresses) { System.out.println("Presence changed: entriesDeleted"); } public void entriesAdded(Collection<String> addresses) { System.out.println("Presence changed: " + addresses.iterator().next()); // Roster.SubscriptionMode.reject_all; } }); } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XMPPException e) { e.printStackTrace(); } Scanner sc = new Scanner(System.in); String str = null; while (!"bye".equals(str = sc.next())) { System.out.println(str); } sc.close(); conn2.disconnect(); }
public void login(JSONObject json, String sessionID) { String username = (String) json.get("nickname"), // "elijah", password = "******", resource = "viewt", serviceName = "openfire-test", // host = "192.168.1.117"; host = "127.0.0.1"; XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() // .setUsernameAndPassword(username, password) .setServiceName(serviceName) .setHost(host) .setPort(5222) // .setDebuggerEnabled(true) .setSecurityMode(SecurityMode.disabled) // .allowEmptyOrNullUsernames() .build(); AbstractXMPPConnection conn = new XMPPTCPConnection(config); MultiUserChatManager mucMgr = null; InvitationListener invitationListener = null; try { conn.connect(); // conn.login(); conn.login(username, password, resource); conn_map.put(session.getId(), conn); sess_map.put(session.getId(), session); user_map.put(username, sessionID); mucMgr = MultiUserChatManager.getInstanceFor(conn); // 邀请监听 A->B invitationListener = new InvitationListener() { @Override public void invitationReceived( XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) { // inviter--conn // A---------->B // java.util.logging.Logger.getLogger(""). // 邀请原因 存放 对方的sessionID JSONObject jsonObject1 = new JSONObject(reason); String mucname = (String) jsonObject1.getString("mucname"); // 邀请原因 JSONObject jsonObject = new JSONObject(jsonObject1.get("reason").toString().replace("'", "\"")); String sessionID = (String) jsonObject.get("sessionID"); // 被邀请人的sessionID String nickname = (String) jsonObject.get("nickname"); // 邀请人昵称 String reason1 = (String) jsonObject.get("reason"); // 邀请原因 try { // = "var rs = {type:'${0}',nickname:'${1}',mucname:'${2}',msg:'${3}'}" String rs1 = rs.replace("${type}", "invited") .replace("${nickname}", nickname) .replace("${reason}", reason1) .replace("${mucname}", mucname); // 发送消息通知对方 sess_map.get(sessionID).getBasicRemote().sendText(rs1); } catch (IOException e) { e.printStackTrace(); } // (conn2, room, inviter, "I'm busy right now"); // try { // room.join(conn.getUser()); // } catch (NoResponseException e) { // e.printStackTrace(); // } catch (XMPPErrorException e) { // e.printStackTrace(); // } catch (NotConnectedException e) { // e.printStackTrace(); // } } }; mucMgr.addInvitationListener(invitationListener); System.out.println("-------" + conn.getStreamId() + "--" + session.getId()); // 这里发送broadcast消息 通知所有在线的人员 broadcast(json, sessionID); } catch (Exception e) { e.printStackTrace(); conn = null; conn_map.remove(session.getId()); sess_map.remove(session.getId()); if (mucMgr != null) mucMgr.removeInvitationListener(invitationListener); } }
/** * 房间创建 * * @param object * @return */ public String createMuc(JSONObject object, String sessionID) { AbstractXMPPConnection connection = conn_map.get(this.session.getId()); String mucName = getName(connection.getUser()) + "-MUC" + CONFERENCE_NAME; String nickName = (String) object.get("nickname"); MultiUserChat muc = null; try { muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(mucName); muc.create(nickName); muc.sendConfigurationForm(new Form(DataForm.Type.submit)); muc.addMessageListener( new MessageListener() { @Override public void processMessage(Message message) { System.out.println("TXT--" + message.toXML()); if (getResource(message.getFrom()).equals(getName(message.getTo()))) return; // sess_map.get(user_map.get(getName(message.getTo()))).getAsyncRemote().sendText(message.getBody()+" -- Hello World"); sess_map .get(user_map.get(getName(message.getTo()))) .getAsyncRemote() .sendText( rs.replace("${type}", "msg") .replace("${msg}", message.getBody() + "--helloworld")); } }); // muc.join(nickName); //加入房间 // 如果成员被邀请进来则通知 muc.addParticipantListener( new PresenceListener() { @Override public void processPresence(Presence presence) { // 监听成员的状态 // broadcast(object, sessionID); Collection<Session> values = sess_map.values(); // String from = presence.getFrom(); Iterator<Session> iterator = values.iterator(); // String rs1 = rs.replace("${type}", "broadcast").replace("${nickname}", // nickname).replace("${sessionID}", sessionID); while (iterator.hasNext()) { try { Session next = iterator.next(); String data = rs.replace("${type}", "ParticipantStatus"); System.out.println(data); if (next.isOpen()) next.getBasicRemote().sendText(data); } catch (IOException e) { e.printStackTrace(); } } } }); // 发送通知到页面 sess_map .get(sessionID) .getBasicRemote() .sendText(rs.replace("${type}", "createMuc").replace("${mucname}", mucName)); } catch (XMPPErrorException | SmackException | IOException e1) { e1.printStackTrace(); } return mucName; }