Android 基于XMPP Smack Openfire 单人聊天和多人聊天(发送消息、接收消息)
一、单人聊天
1)发送消息:
首先要获取一个聊天窗口,getConnection()为获取连接connection的方法,调用getFriendChat()获取
private Map<String, Chat> chatManage = new HashMap<String, Chat>();// 聊天窗口管理map集合 /** * 获取或创建聊天窗口 * @param friend 好友名 * @param listenter 聊天監聽器 * @return */ public Chat getFriendChat(String friend, MessageListener listenter) { if(getConnection()==null) return null; /** 判断是否创建聊天窗口 */ for (String fristr : chatManage.keySet()) { if (fristr.equals(friend)) { // 存在聊天窗口,则返回对应聊天窗口 return chatManage.get(fristr); } } /** 创建聊天窗口 */ Chat chat = getConnection().getChatManager().createChat(friend + "@"+ getConnection().getServiceName(), listenter); /** 添加聊天窗口到chatManage */ chatManage.put(friend, chat); return chat; }
Chat chat = getFriendChat(friend,null); try { String msgjson = "{"messageType":""+messageType+"","chanId":""+chanId+"","chanName":""+chanName+""}"; chat.sendMessage(msgjson); } catch (XMPPException e) { e.printStackTrace(); }
import org.jivesoftware.smack.Chat;import org.jivesoftware.smack.ChatManagerListener;import org.jivesoftware.smack.MessageListener;import org.jivesoftware.smack.packet.Message;import org.jivesoftware.smack.util.StringUtils;import org.json.JSONException;import org.json.JSONObject;import com.techrare.utils.XmppConnection;/** * 单人聊天信息监听类 * * @author Administrator * */public class TaxiChatManagerListener implements ChatManagerListener {public void chatCreated(Chat chat, boolean arg1) {chat.addMessageListener(new MessageListener() {public void processMessage(Chat arg0, Message msg) {//登录用户StringUtils.parseName(XmppConnection.getInstance().getConnection().getUser());//发送消息用户msg.getFrom();//消息内容String body = msg.getBody();boolean left = body.substring(0, 1).equals("{");boolean right = body.substring(body.length()-1, body.length()).equals("}");if(left&&right){try {JSONObject obj = new JSONObject(body);String type = obj.getString("messageType");String chanId = obj.getString("chanId");String chanName = obj.getString("chanName");} catch (JSONException e) {e.printStackTrace();}}}});}}
TaxiChatManagerListener chatManagerListener = new TaxiChatManagerListener(); getConnection().getChatManager().addChatListener(chatManagerListener);
connection.getChatManager().removeChatListener(chatManagerListener);
/** * 创建房间 * * @param roomName 房间名称 */public MultiUserChat createRoom(String user, String roomName,String password) {if (getConnection() == null)return null;MultiUserChat muc = null;try {// 创建一个MultiUserChatmuc = new MultiUserChat(getConnection(), roomName + "@conference."+ getConnection().getServiceName());// 创建聊天室muc.create(roomName);// 获得聊天室的配置表单Form form = muc.getConfigurationForm();// 根据原始表单创建一个要提交的新表单。Form submitForm = form.createAnswerForm();// 向要提交的表单添加默认答复for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {FormField field = (FormField) fields.next();if (!FormField.TYPE_HIDDEN.equals(field.getType())&& field.getVariable() != null) {// 设置默认值作为答复submitForm.setDefaultAnswer(field.getVariable());}}// 设置聊天室的新拥有者List<String> owners = new ArrayList<String>();owners.add(getConnection().getUser());// 用户JIDsubmitForm.setAnswer("muc#roomconfig_roomowners", owners);// 设置聊天室是持久聊天室,即将要被保存下来submitForm.setAnswer("muc#roomconfig_persistentroom", true);// 房间仅对成员开放submitForm.setAnswer("muc#roomconfig_membersonly", false);// 允许占有者邀请其他人submitForm.setAnswer("muc#roomconfig_allowinvites", true);if (!password.equals("")) {// 进入是否需要密码submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",true);// 设置进入密码submitForm.setAnswer("muc#roomconfig_roomsecret", password);}// 能够发现占有者真实 JID 的角色// submitForm.setAnswer("muc#roomconfig_whois", "anyone");// 登录房间对话submitForm.setAnswer("muc#roomconfig_enablelogging", true);// 仅允许注册的昵称登录submitForm.setAnswer("x-muc#roomconfig_reservednick", true);// 允许使用者修改昵称submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);// 允许用户注册房间submitForm.setAnswer("x-muc#roomconfig_registration", false);// 发送已完成的表单(有默认值)到服务器来配置聊天室muc.sendConfigurationForm(submitForm);} catch (XMPPException e) {e.printStackTrace();return null;}return muc;}
/** * 加入会议室 * * @param user * 昵称 * @param password * 会议室密码 * @param roomsName * 会议室名 */public MultiUserChat joinMultiUserChat(String user, String roomsName,String password) {if (getConnection() == null)return null;try {// 使用XMPPConnection创建一个MultiUserChat窗口MultiUserChat muc = new MultiUserChat(getConnection(), roomsName+ "@conference." + getConnection().getServiceName());// 聊天室服务将会决定要接受的历史记录数量DiscussionHistory history = new DiscussionHistory();history.setMaxChars(0);// history.setSince(new Date());// 用户加入聊天室muc.join(user, password, history,SmackConfiguration.getPacketReplyTimeout());Log.i("MultiUserChat", "会议室【"+roomsName+"】加入成功........");return muc;} catch (XMPPException e) {e.printStackTrace();Log.i("MultiUserChat", "会议室【"+roomsName+"】加入失败........");return null;}}
try { multiUserChat.sendMessage(message); } catch (XMPPException e) { e.printStackTrace(); }
import org.jivesoftware.smack.PacketListener;import org.jivesoftware.smack.packet.Message;import org.jivesoftware.smack.packet.Packet;/** * 会议室消息监听类 * * @author Administrator * */public class TaxiMultiListener implements PacketListener {@Overridepublic void processPacket(Packet packet) {Message message = (Message) packet;String body = message.getBody();}}
multiUserChat.addMessageListener(new TaxiMultiListener());