smack 4.3.3 群聊实现

1.环境参考上一篇

 

2.demo

package com.tt.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence; 
import org.jivesoftware.smack.roster.Roster; 
import org.jivesoftware.smack.roster.RosterListener;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.bookmarks.BookmarkedConference;
import org.jivesoftware.smackx.bookmarks.Bookmarks;
import org.jivesoftware.smackx.iqprivate.PrivateDataManager;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MucConfigFormManager;
import org.jivesoftware.smackx.muc.MucEnterConfiguration;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatException.MucConfigurationNotSupportedException;
import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.muc.packet.GroupChatInvitation;
import org.jivesoftware.smackx.offline.OfflineMessageManager;
import org.jivesoftware.smackx.xdata.Form;
import org.jivesoftware.smackx.xdata.FormField;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.EntityFullJid;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.stringprep.XmppStringprepException;
 

public class XmppClient7 {
	
	static AbstractXMPPConnection connection;
	static MultiUserChat chatRoom; 
	public void login(String userName, String password) throws Exception {
		 
	   XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
				  .setUsernameAndPassword(userName, password)
				  .setXmppDomain("localhost.vm")
				  .setHost("localhost.vm")
				  .setPort(5222)
				  .setSendPresence(false)//璁剧疆涓嶅彂閫丳resence
				  .setSecurityMode(SecurityMode.disabled) // Do not disable TLS except for test purposes!
				  .build();

		connection = new XMPPTCPConnection(config);
		connection.connect().login(); 
	}
  	 	 
	
	public void disconnect() throws NotConnectedException, InterruptedException {
		setOfflineStatus();
		connection.disconnect();
	} 
	
	public void handleOfflineMessages() throws Exception {
        OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);

        if (!offlineMessageManager.supportsFlexibleRetrieval()) {
        	System.out.println("no support offline");
            return;
        }

        if (offlineMessageManager.getMessageCount() == 0) {
            String d = "ss";
        } else {
            List<Message> msgs = offlineMessageManager.getMessages();
            for (Message msg : msgs) {
                BareJid fullJid = msg.getFrom().asBareJid();
                String messageBody = msg.getBody();
                if (messageBody != null) {

                }
            }
            // offlineMessageManager.deleteMessages();
        }

    }
 
	public void setOnlineStatus() throws NotConnectedException, InterruptedException { 	
		Presence presence = new Presence(Presence.Type.available, "online", 1 , Presence.Mode.available); 
		connection.sendStanza(presence);		
		Presence presence2 = new Presence(Presence.Type.subscribe, "online", 1 , Presence.Mode.available); 
		connection.sendStanza(presence2);		
		Presence presence3 = new Presence(Presence.Type.subscribed, "online", 1 , Presence.Mode.available); 
		connection.sendStanza(presence3);		
	}
	public void setOfflineStatus() throws NotConnectedException, InterruptedException {
		Presence presence = new Presence(Presence.Type.available, "Gone fishing", 2 , Presence.Mode.away); 
		connection.sendStanza(presence);		
		Presence presence2 = new Presence(Presence.Type.subscribe, "Gone fishing", 2 , Presence.Mode.away); 
		connection.sendStanza(presence2);		
		Presence presence3 = new Presence(Presence.Type.subscribed, "Gone fishing", 2 , Presence.Mode.away); 
		connection.sendStanza(presence3);		
	}
	
 
  
		public int showJoinRoom() {
			Set<EntityBareJid> room = MultiUserChatManager.getInstanceFor(connection).getJoinedRooms(); 
			System.out.println("Get Room count : " + room.size()); 
			for(EntityBareJid r : room) {
				System.out.println("Get Room name : " + r.toString());
			}
			return room.size();
		} 
		 
		
	    public void setMucConfig() throws MucConfigurationNotSupportedException {  
			try {
				MucConfigFormManager form = chatRoom.getConfigFormManager();
		        form.makePasswordProtected();
		        form.setAndEnablePassword("test"); 
		        form.submitConfigurationForm(); 
			} catch (NoResponseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XMPPErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NotConnectedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	    }

	    public String getJid(String user) {
	    	return user + "@" + connection.getHost();
	    } 
	    public  EntityBareJid getMucJid(String groupName) throws XmppStringprepException {
	    	 return JidCreate.entityBareFrom(groupName + "@muc." + connection.getHost());
	    } 
	    public void JoinMultChat(String groupName, String nickName, String pwd) throws XmppStringprepException, NotAMucServiceException, XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException, MucConfigurationNotSupportedException {
  
	    	chatRoom = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(getMucJid(groupName)); 
	    	
	    	MucEnterConfiguration.Builder builder = chatRoom.getEnterConfigurationBuilder(Resourcepart.from(nickName));
	      	builder.requestMaxStanzasHistory(1);  
	    	//builder.requestNoHistory();
	    	builder.withPassword(pwd);
	    	MucEnterConfiguration mucEnterConfiguration = builder.build();
	    	chatRoom.join(mucEnterConfiguration);  
	    	setMucConfig();
	    } 
	    public void startMultChat() throws NotConnectedException, InterruptedException, IOException { 
 
	    	chatRoom.addMessageListener(new MessageListener(){
                public void processMessage(Message message)
                {
                	if(Message.Type.groupchat  == message.getType() && message.getBody() != null)
                	{
                		System.out.println(message.getFrom()+":" + message.getBody());  
                	} 
                }
            });
	    	
			String msg = "";
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("start you multchat:");
			while (!(msg = br.readLine()).equals("bye")) {  
				try {
					chatRoom.sendMessage(msg);
				} catch (NotConnectedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace(); 
				}
			} 
			chatRoom.leave();
	    } 
		public void startPrivateMultChat(String jid) throws InterruptedException, IOException, NotConnectedException {
			// Start a new conversation with John Doe and send him a message.

		   ChatManager chatManager = ChatManager.getInstanceFor(connection);
		
		  chatManager.addIncomingListener(new IncomingChatMessageListener() {
		
		      public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
		
		       // Print out any messages we get back to standard out.
		
				System.out.print(message.getFrom() + ":" + message.getBody());
		
		       }
		
		   });

			System.out.println("build a chat for " + jid);
			System.out.println("start you private chat:");
			
			Chat priChat = chatManager.chatWith(JidCreate.entityBareFrom(jid));
		
			String msg = "";
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
			while (!(msg = br.readLine()).equals("bye")) {  
				try { 
					priChat.send(msg);
				} catch (NotConnectedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace(); 
				}
			}   
	    }
		/*
		 * create a persistentroom
		 */

	    public MultiUserChat createMultRoom(String groupName) throws Exception {
  
	        MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(getMucJid(groupName));
	        String nickName = groupName;
	        muc.create(Resourcepart.from(nickName));

	        chatRoom = muc;
	        setMucConfig();
	        
	        // 获得聊天室的配置表单

	        Form form = muc.getConfigurationForm();

	        // 根据原始表单创建一个要提交的新表单。

	        Form submitForm = form.createAnswerForm();  
	        

	        //设置为公共房间

	        submitForm.setAnswer("muc#roomconfig_publicroom", true);

	        // 设置聊天室是持久聊天室,即将要被保存下来

	        submitForm.setAnswer("muc#roomconfig_persistentroom", true); 

	        // 发送已完成的表单(有默认值)到服务器来配置聊天室

	        muc.sendConfigurationForm(submitForm);
	        
	        return muc;

	    }
		/*
		 *只有 persistentroom 需要 destroy来释放
		 */
		public void destroyMuc() throws NoResponseException, XMPPErrorException, NotConnectedException, XmppStringprepException, InterruptedException {

			EntityBareJid jid = chatRoom.getRoom();
	        chatRoom.destroy("I'm leave", jid);
	        System.out.println("destroy this room" + jid);
		}
		public void showAllroom() throws NotAMucServiceException, NoResponseException, XMPPErrorException, NotConnectedException, XmppStringprepException, InterruptedException {
			DomainBareJid domainJid = JidCreate.domainBareFrom("muc." + connection.getHost());
			Map<EntityBareJid, HostedRoom> roomsInfo = MultiUserChatManager.getInstanceFor(connection).getRoomsHostedBy(domainJid);
			System.out.println("show All see rooms:");
			for (Map.Entry<EntityBareJid, HostedRoom> entry : roomsInfo.entrySet()) { 
				//  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
				  System.out.println(entry.getKey());
			}
		}
	    public static void doMuc(XmppClient7 c) throws Exception {
	    	 
			String groupRoom="TestGroup1"; 
			c.showAllroom();
			if(c.showJoinRoom() < 1)
			{
				c.JoinMultChat(groupRoom, "hells", "test");
			} 
			if(c.showJoinRoom() > 0)
			{ 
				c.startMultChat();
				//c.startPrivateMultChat(getJid("tzj101"));
			} 
	    }
	public static void main(String args[]) throws Exception {

		XmppClient7 c = new XmppClient7();  
		c.login("hells", "1");  
		
		c.handleOfflineMessages();
		c.setOnlineStatus();
		doMuc(c);
		c.disconnect(); 
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值