zoukankan      html  css  js  c++  java
  • openfire+smack 实现即时通讯基本框架

    smack jar下载地址 http://www.igniterealtime.org/downloads/download-landing.jsp?file=smack/smack_3_2_2.zip

    由于项目需要,开始搞即时通讯相关技术,最后敲定openfire+smack实现,保留部分测试代码,留作参考:

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    
    import org.jivesoftware.smack.Connection;
    import org.jivesoftware.smack.ConnectionConfiguration;
    import org.jivesoftware.smack.Roster;
    import org.jivesoftware.smack.RosterEntry;
    import org.jivesoftware.smack.RosterGroup;
    import org.jivesoftware.smack.XMPPConnection;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.packet.Presence;
    import org.jivesoftware.smackx.Form;
    import org.jivesoftware.smackx.ReportedData;
    import org.jivesoftware.smackx.ReportedData.Row;
    import org.jivesoftware.smackx.search.UserSearchManager;
    
    /**
     * 即时通讯帮助类
     * @作者 : hyw
     * @描述 : TODO
     * @创建时间 : 2014-8-20 上午9:49:53
     * @修改时间 : 2014-8-20 上午9:49:53
     * @version : 1.0
     */
    public class ChatHelper {
        /**
         * 初始Smack对openfire服务器链接的基本配置
        * @方法名称: init 
        * @描述: TODO
         */
    	public static Connection getConnection(String chatServerAddress,Integer port) {
    		Connection connection = null;
    		
    		try {
                /** 5222是openfire服务器默认的通信端口,你可以登录http://192.168.8.32:9090/到管理员控制台查看客户端到服务器端口 */
    			ConnectionConfiguration config = new ConnectionConfiguration(chatServerAddress, port);
                
                /** 是否启用压缩 */ 
                config.setCompressionEnabled(true);
                /** 是否启用安全验证 */
                config.setSASLAuthenticationEnabled(true);
                /** 是否启用调试 */
                config.setDebuggerEnabled(false);
                //config.setReconnectionAllowed(true);
                //config.setRosterLoadedAtLogin(true);
                
                /** 创建connection链接 */
                connection = new XMPPConnection(config);
                /** 建立连接 */
                connection.connect();
            } catch (XMPPException e) {
                e.printStackTrace();
            }
    		
    		return connection;
        }
    	
    	
    	    //添加用户组
    	    public static void createGroup(Connection connection, String groupName){
    	    	Roster roster = connection.getRoster();
    	    	RosterGroup rosterGroup = roster.createGroup(groupName);
    	    }
    	    
    	    //更新用户组
    		 public static boolean updateGroup(Connection connection, String oldGroupName,String newGroupName) {
    				  try {
    				   Roster roster = connection.getRoster();
    				   RosterGroup rosterGroup = roster.getGroup(oldGroupName);
    				   
    				   //获取该组下所有用户
    				   Collection<RosterEntry> entrys = rosterGroup.getEntries();
    				   
    				   rosterGroup.setName(newGroupName);
    				   String[] groups = new String[] { newGroupName };
    				   if (rosterGroup != null) {
    				 	    try {
    				 	     Iterator<RosterEntry> it = entrys.iterator();
    				 	     while (it.hasNext()) {
    				 	      RosterEntry rosterEntry = (RosterEntry) it.next();
    				 	     roster.createEntry(rosterEntry.getUser(), rosterEntry.getName(), groups);
    				 	      
    				 	      
    				 	     }
    				 	    } catch (XMPPException e) {
    				 	     e.printStackTrace();
    				 	    }
    				    	
    				 	   }
    				   
    				   return true;
    				  } catch (Exception e) {
    				   e.printStackTrace();
    				   return false;
    				  }
    				 }
    	    
    	    
    	    //向用户组添加用户
    	    public static void addUserInGroup(Connection connection,String groupName,String userId,String nickName){
    	    	
    	    	
    	       Roster roster = connection.getRoster();
    	 	   String[] groups = new String[] { groupName };
    	 	   try {
    			roster.createEntry(userId, nickName, groups);
    		} catch (XMPPException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    	 	   RosterGroup rosterGroup = roster.getGroup(groupName);
    	 	   Collection entrys = rosterGroup.getEntries();
    	 	   if (rosterGroup != null) {
    	 	    try {
    	 	     Iterator it = entrys.iterator();
    	 	     while (it.hasNext()) {
    	 	      RosterEntry rosterEntry = (RosterEntry) it.next();
    	 	      rosterGroup.addEntry(rosterEntry);
    	 	     }
    	 	    } catch (XMPPException e) {
    	 	     e.printStackTrace();
    	 	    }
    	    	
    	 	   }
    	    }
    	    
    	    
    	    /**
    		 * 删除一个好友
    		 * @param roster
    		 * @param userName
    		 * @return
    		 */
    		public static boolean removeUser(Connection connection,String userName){
    			Roster roster = connection.getRoster();
    			try {
    				
    				if(userName.contains("@"))
    				{
    					userName = userName.split("@")[0];
    				}
    				RosterEntry entry = roster.getEntry(userName);
    				System.out.println("删除好友:"+userName);
    				System.out.println("User: "+(roster.getEntry(userName) == null));
    				roster.removeEntry(entry);
    				
    				return true;
    			} catch (Exception e) {
    				e.printStackTrace();
    				return false;
    			}
    			
    		}
    	    
    	    //用户登录
    	    public static boolean login(Connection connection,String username, String password ){
    	    	
    	    	boolean loginResult = true;
    	    	
    	    	try {
    				connection.login(username, password);
    			} catch (XMPPException e) {
    				loginResult = false;
    				e.printStackTrace();
    			}
    	    	return loginResult;
    	    }
    	    
    	    //按用户名,查询用户
    	    public static void searchUsers(Connection connection,String serverDomain,String userName) throws XMPPException
    		{
    			UserSearchManager usm = new UserSearchManager(connection);
    	        Form searchForm = usm.getSearchForm(serverDomain);
    	        Form answerForm = searchForm.createAnswerForm();
    	        answerForm.setAnswer("Username", true);
    	        answerForm.setAnswer("search", userName);
    	        ReportedData data = usm.getSearchResults(answerForm, serverDomain);
    			 
    			 Iterator<Row> it = data.getRows();
    			 Row row = null;
    			 while(it.hasNext())
    			 {
    				 row = it.next();
    				 System.out.println(row.getValues("Username").next());
    				 System.out.println(row.getValues("Name").next());
    				 System.out.println(row.getValues("Email").next());
    				 //若存在,则有返回,UserName一定非空,其他两个若是有设,一定非空
    			 }
    		}
    
    	    /**
    		 * 返回所有组信息 <RosterGroup>
    		 * 
    		 * @return List(RosterGroup)
    		 */
    		public static void getGroups(Connection connection) {
    			Roster roster = connection.getRoster();
    			Collection<RosterGroup> rosterGroup = roster.getGroups();
    			Iterator<RosterGroup> i = rosterGroup.iterator();
    			while (i.hasNext())
    				System.out.println(i.next().getName());
    		}
    	    
    		
    		
    		 //获取所有好友
    		 public static void getAllEntries(Connection connection) {
    			 Roster roster = connection.getRoster();
    			  Collection<RosterEntry> rosterEntry = roster.getEntries();
    			  Iterator<RosterEntry> i = rosterEntry.iterator();
    			  while (i.hasNext()) {
    				  RosterEntry rosterEntity = i.next();
    				  System.out.println(rosterEntity.getUser());
    				  System.out.println(rosterEntity.getName());
    				  System.out.println(rosterEntity.getStatus());
    				  System.out.println(rosterEntity.getType());
    			  }
    			 }
    		
    	    
    		//获取我的好友树
    		public static void getGroupTree(Connection connection) {
    			System.out.println("好友树列表");
    			Roster roster = connection.getRoster();
    			Collection<RosterGroup> entriesGroup = roster.getGroups();
    			for (RosterGroup group : entriesGroup) {
    				Collection<RosterEntry> entries = group.getEntries();
    				System.out.println(group.getName());
    				for (RosterEntry entry : entries) {
    					System.out.println(entry.getUser());
    					System.out.println(roster.getPresence(entry.getUser()));
    					Presence presence = roster.getPresence(entry.getUser());
    					System.out.println("状态:" + presence.getStatus());
    					System.out.println("name: " + entry.getName());
    				}
    			}
    		}
    		 
    		
    		// 获取未分组好友
    		public static void getUnFriendsContanct(Connection connection) {
    			Collection<RosterEntry> rosterPerson = connection.getRoster()
    					.getUnfiledEntries();
    			System.out.println("获取未分组好友:=======================");
    			for (RosterEntry rosterEntry : rosterPerson) {
    				System.out.println("name: " + rosterEntry.getName() + ",jid: "
    						+ rosterEntry.getUser());
    			}
    		}
    	    
    		
    		
    		 //获取在线用户
    		 public static void getOnlineUser(Connection connection) {
    		  try {
    		   Roster roster = connection.getRoster();
    		   Collection<RosterEntry> entries = roster.getEntries();
    		   if (entries!=null) {
    		    for (RosterEntry entry : entries) {
    		     // 获取好友状态
    		     Presence presence = roster.getPresence(entry.getUser());
    		     if (presence.isAvailable() == true) {
    		      System.out.println(presence.getStatus());
    		      System.out.println(entry.getUser());
    		         System.out.println(entry.getName());
    		     }
    		    }
    		   }
    		  } catch (Exception e) {
    		   e.printStackTrace();
    		  }
    		 }
    		
    		
    		
    		
    		
    	    
    	    public static void main(String[] args) {
    	    	
    	    	 Connection connection;
    	        /** openfire服务器address */
    	         String chatServerAddress = "192.168.1.234";
    	         connection = ChatHelper.getConnection(chatServerAddress, 5222);
    	    	 login(connection,"hyw","admin");
    	    	 
    	    	 //创建组
    	    	 //ChatHelper.createGroup(connection, "myGroup");
    	    	 
    	    	//向组内添加用户
    	    	// ChatHelper.addUserInGroup(connection,"myGroup","wlh@192.168.1.234/Smack","凌辉");
    	    	 
    	    	 
    	    	 //更新组名称
    	    	 //ChatHelper.updateGroup(connection, "myGroup", "testGroup");
    	    	 
    	    	 //获取用户所有分组
    	    	 //ChatHelper.getGroups(connection);
    	    	 
    	    	 //获取所有好友
    	    	 //ChatHelper.getAllEntries(connection);
    	    	 
    	    	 //获取我的好友列表树
    	    	 //ChatHelper.getGroupTree(connection);
    	    	 
    	    	 
    	    	 //查询好友
    	    	 try {
    				ChatHelper.searchUsers(connection, chatServerAddress, "wlh");
    			} catch (XMPPException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    	    	 
    		}
        
    }
    

      

  • 相关阅读:
    图书馆管理系统

    有理数类的设计
    题目4-多关键字排序(基于自定义比较函数)
    图总结
    树、二叉树、查找算法总结
    数据结构小结
    C语言文件
    第二次博客作业
    第一次博客作业
  • 原文地址:https://www.cnblogs.com/angryprogrammer/p/3924791.html
Copyright © 2011-2022 走看看