简单练手源码:openfire+smack创建会议室和创建群

 package com.test.chat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.ExceptionCallback;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotLoggedInException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PacketCollector.Configuration;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection.FromMode;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.iqrequest.IQRequestHandler;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.PlainStreamElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.RosterGroup;
import org.jivesoftware.smack.roster.RosterListener;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration.Builder;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jivesoftware.smackx.iqregister.packet.Registration;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.xdata.Form;
import org.jivesoftware.smackx.xdata.FormField;
public class Connection {
 // /创建需要的参数
 public String username = "admin";
 public String password = "admin";
 public String servicename = "localhost";
 public AbstractXMPPConnection conn = null;
 public Connection() {
  this.createcon();
 }
 public AbstractXMPPConnection getConn() {
  return conn;
 }
 public void createcon() {
  // 创建连接
  Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
  configBuilder.setUsernameAndPassword(username, password);
  configBuilder.setHost("127.0.0.1");
  configBuilder.setSecurityMode(SecurityMode.disabled);// 不支持TLS验证
  configBuilder.setSendPresence(true);
  configBuilder.setPort(5222);
  configBuilder.setResource("web");
  // configBuilder.setDebuggerEnabled(true);
  configBuilder.setServiceName(servicename);
  conn = new XMPPTCPConnection(configBuilder.build());
  try {
   conn.connect().login();
   // System.out.println("Esta conectat? "+ conn.connect());
   // conn.login();
   // System.out.println("连接ok!");
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
  // closed Datasource
  
 }
 // closed comet connection
 public void disconnect() {
  if (conn != null) {
   conn.disconnect();
  }
 }
/**
 * core method
 */
 
 public static void createRoom() {
  // TODO Auto-generated method stub
  AbstractXMPPConnection conn = null;
  try {
   Builder builder = XMPPTCPConnectionConfiguration.builder();
   builder.setSecurityMode(SecurityMode.disabled);
   XMPPTCPConnectionConfiguration config = builder
     .setUsernameAndPassword("admin", "admin")
     .setServiceName("localhost").setHost("localhost")
     .setPort(5222).build();
   conn = new XMPPTCPConnection(config);
   conn.connect();
   conn.login();
   // Get the MultiUserChatManager
   MultiUserChatManager manager = MultiUserChatManager
     .getInstanceFor(conn);
   // Create a MultiUserChat using an XMPPConnection for a room
   MultiUserChat muc = manager
     .getMultiUserChat("a1@conference.localhost");
   // Create the room
   muc.create("a1");
   // join user
   /*
    * DiscussionHistory history = new DiscussionHistory();
    * history.setMaxStanzas(5); muc.join("test2", "admin", history,
    * conn.getPacketReplyTimeout());
    */
   // Get the the room's configuration form
   Form form = muc.getConfigurationForm();
   // Create a new form to submit based on the original form
   Form submitForm = form.createAnswerForm();
   // Add default answers to the form to submit
   for (Iterator fields = form.getFields().iterator(); fields
     .hasNext();) {
    FormField field = (FormField) fields.next();
    if (!FormField.Type.hidden.equals(field.getType())
      && field.getVariable() != null) {
     // Sets the default value as the answer
     submitForm.setDefaultAnswer(field.getVariable());
    }
   }
   // Sets the new owner of the room
   List owners = new ArrayList();
   owners.add("admin@localhost");
   submitForm.setAnswer("muc#roomconfig_roomowners", owners);
   submitForm.setAnswer("muc#roomconfig_persistentroom", true);
   // Send the completed form (with default values) to the server to
   // configure the room
   muc.sendConfigurationForm(submitForm);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (conn != null) {
    try {
     conn.disconnect();
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 // 创建用户加入聊天室
 public static void joinChatRoom(String roomName, String nickName) {
  AbstractXMPPConnection conn = null;
  try {
   Builder builder = XMPPTCPConnectionConfiguration.builder();
   builder.setSecurityMode(SecurityMode.disabled);
   XMPPTCPConnectionConfiguration config = builder
     .setUsernameAndPassword("admin", "admin")
     .setServiceName("localhost").setHost("localhost")
     .setPort(5222).build();
   conn = new XMPPTCPConnection(config);
   conn.connect();
   conn.login();
   MultiUserChat muc = null;
   muc = MultiUserChatManager.getInstanceFor(conn).getMultiUserChat(
     roomName + "@conference." + conn.getServiceName());
   // 聊天室服务将会决定要接受的历史记录数量
   DiscussionHistory history = new DiscussionHistory();
   history.setMaxChars(0);
   // history.setSince(new Date());
   // 用户加入聊天室
   muc.join(nickName);
   // muc.sendMessage("hello!");
   System.out.println("MultiUserChat ok!");
   while (true) {
   }
   // return muc;
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
   System.out.println("MultiUserChat ko!");
  }
 }
 /**
  * * 获取所有组
  * @param roster
  * @return 所有组集合
  */
 public static List<RosterGroup> getGroups(Roster roster) {
  
  List<RosterGroup> grouplist = new ArrayList<RosterGroup>();
  Collection<RosterGroup> rosterGroup = roster.getGroups();
  Iterator<RosterGroup> i = rosterGroup.iterator();
  while (i.hasNext()) {
   grouplist.add(i.next());
  }
  return grouplist;
 }
 
 /**
  * 获取某个组里面的所有好友
  * @param roster
  * @param groupName
  * 组名
  * @return
  */
 public static List<RosterEntry> getEntriesByGroup(Roster roster,
   String groupName) {
  try {
  } catch (Exception e) {
   // TODO: handle exception
  }
  List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
  RosterGroup rosterGroup = roster.getGroup(groupName);
  Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();
  Iterator<RosterEntry> i = rosterEntry.iterator();
  while (i.hasNext()) {
   Entrieslist.add(i.next());
  }
  return Entrieslist;
 }
 
    /** 
     * 添加好友 有分组 
     * @param roster 
     * @param userName 
     * @param name 
     * @param groupName 
     * @return 
     */  
    public static boolean addUser(Roster roster, String userName, String name,  
            String groupName) { 
     
     
        try {  
            roster.createEntry(userName, name, new String[] { groupName });  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    } 
 // test connection
 public static void main(String[] args) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException {
  Connection con = new Connection();
  Roster roster1 = Roster.getInstanceFor(con.getConn());
//  roster1.createGroup("博士");
//  roster1.createEntry("123@localhost", "boshi", new String[]{"博士"});
  // createRoom();
  // joinChatRoom("a1", "a2");
  try {

   //获取组列表
//   List group = new ArrayList(); 
//   for(RosterGroup g:getGroups(roster1)){
//    System.out.println(g.getName());
//   }
    //获取好友列表
//    List haoyou =new ArrayList();
//    List<RosterEntry> l = getEntriesByGroup(roster1,"rrrrrr");
//    for (int i = 0; i < l.size(); i++) {
//     haoyou.add(l.get(i).getName());
//   }
//    System.out.println(haoyou);
    
    
    List<RosterEntry> ls = getEntriesByGroup(roster1,"博士");
    for(RosterEntry e:ls){
     System.out.println(e.getName());
   }
    con.disconnect();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
  
  //addUser(roster1, "test", "lisi","group1");
  
}
 }

转载于:https://my.oschina.net/u/2376544/blog/598329

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值