从:http://blog.csdn.net/casuallc/article/details/34794501
server:openfire
client计划:smark写
首先安装openfire,下载client直接安装就可以。数据库能够用openfire自身的,也能够用自己的数据库,仅仅要按提示设置好參数就可以
之后,就能够用smark写一个client測试与openfire的通信了(须要引进的jar包除了smark自身的。还要引入xmlpull-1.1.3.1.jar、kxml2-2.3.0.jar两个包
,作用是解析xml文件)
备注:我用的smark版本号是4.0。要引入的基本包有smack-core-4.0.0.jar、smack-debug-4.0.0.jar、smack-extensions-4.0.0.jar、smack-tcp-4.0.0.jar
debug包使用来调试的。tcp是用来初始化连接的、extension包里面含有发送离线消息、文件等类
以下是创建一个连接
- ConnectionConfiguration config = new ConnectionConfiguration("ip", 5222);
-
- config.setSecurityMode(SecurityMode.disabled);
-
- config.setDebuggerEnabled(true);
-
- config.setSendPresence(false);
-
- XMPPConnection conn = new XMPPTCPConnection(config);
-
- conn.setPacketReplyTimeout(5000);
- conn.connect();
-
- conn.login("admin", "0", "资源名");
关于连接的參数,在新版本号中所有在config中设置
发送消息
- private void testSendMessage(XMPPConnection conn) throws Exception {
- //jid在数据表中ofroster能够查到。通常是 username@server名称
- Chat chat = ChatManager.getInstanceFor(conn).createChat("ly@192.168.1.100", new MessageListener() {
- @Override
- public void processMessage(Chat chat, Message message) {
- System.out.println("Received message: " + message);
- }
- });
- Message msg = new Message();
- msg.setBody("hello world");
- //定义成normal,在对象不在线时发送离线消息。消息存放在数据表ofoffline中
- msg.setType(Message.Type.normal);
- //发送消息。參数能够是字符串,也能够是message对象
- chat.sendMessage(msg);
- //发送广播
- conn.sendPacket(msg);
- }
发送离线消息
- private void testOffLine(XMPPConnection conn) throws Exception {
-
- OfflineMessageManager offMM = new OfflineMessageManager(conn);
- System.out.println("离线文件数量 :" + offMM.getMessageCount());
- System.out.println("离线文件内容 :");
-
-
- List<Message> listMessage = offMM.getMessages();
-
- System.out.println(listMessage.size());
- for(Message m : offMM.getMessages()) {
- System.out.println(" 离线 : " + m.getBody() + m.getBodies());
- }
- }
得到好友列表
- private void testGetRoster(XMPPConnection conn) throws Exception {
-
- Roster r = conn.getRoster();
- Collection<RosterEntry> c = r.getEntries();
- for(RosterEntry re : c) {
- StringBuilder sb = new StringBuilder();
- sb.append("name : ").append(re.getName());
- sb.append("\nuser : ").append(re.getUser());
- sb.append("\ntype : ").append(re.getType());
- sb.append("\nstatus : ").append(re.getStatus());
- System.out.println(sb.toString());
- System.out.println("-----------------------------");
- }
- System.out.println(r.getEntries());
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
管理好友,监听好友请求
- <pre name="code" class="java">
- </pre><pre name="code" class="java">private void testAddAndDelFriends(final XMPPConnection conn) throws Exception {
- Roster r = conn.getRoster();
-
-
-
-
-
-
-
- PacketListener packetListener = new PacketListener() {
-
- @Override
- public void processPacket(Packet packet) throws NotConnectedException {
-
-
-
-
-
-
-
-
-
- Presence presence = (Presence) packet;
- Type type = presence.getType();
-
- if(Type.subscribe.equals(type)) {
-
-
-
-
-
-
-
-
-
-
-
-
- presence.setType(Type.unsubscribed);
-
- presence.setTo(presence.getFrom());
- presence.setPacketID(presence.getPacketID());
- Roster r = conn.getRoster();
- try {
- RosterEntry entry = r.getEntry(presence.getFrom());
- if(entry != null)
- r.removeEntry(entry);
- } catch (NotLoggedInException | NoResponseException | XMPPErrorException e) {
-
- e.printStackTrace();
- }
- conn.sendPacket(presence);
-
- } else if(Type.unsubscribe.equals(type)) {
- presence.setTo(presence.getFrom());
- presence.setType(Type.unsubscribe);
- Roster r = conn.getRoster();
- try {
- r.removeEntry(r.getEntry(presence.getFrom()));
- } catch (NotLoggedInException | NoResponseException | XMPPErrorException e) {
-
- e.printStackTrace();
- }
- conn.sendPacket(presence);
- }
- }
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
- PacketFilter packetFilter = new AndFilter(new PacketTypeFilter(Presence.class));
-
- conn.addPacketListener(packetListener, packetFilter);
-
-
-
- RosterExchangeManager rem = new RosterExchangeManager(conn);
- rem.addRosterListener(new RosterExchangeListener() {
-
- @Override
- public void entriesReceived(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
- System.out.println(from);
- while(remoteRosterEntries.hasNext()) {
- RemoteRosterEntry entry = remoteRosterEntries.next();
- System.out.println(entry.getUser() + " : " + entry.getName());
- }
- }
-
- });
- }
得到好友的信息。主要是VCard类的使用
- private void testGetFriendInfo(XMPPConnection conn) throws Exception {
- VCard vCard = new VCard();
- VCardManager vcManager = new VCardManager();
-
- boolean b = vcManager.isSupported("ly@192.168.1.100", conn);
- System.out.println(b);
- vCard.load(conn, "ly@192.168.1.100");
-
- byte[] avatarBytes = vCard.getAvatar();
-
- if(avatarBytes == null) {
- return;
- }
-
-
- ImageIcon icon = new ImageIcon(avatarBytes);
- System.out.println(icon.getIconWidth() + " : " + icon.getIconHeight());
-
-
- ByteArrayInputStream bais = new ByteArrayInputStream(avatarBytes);
- try {
- Image image = ImageIO.read(bais);
- FileOutputStream fos = new FileOutputStream("D://icon.jpg");
- fos.write(avatarBytes);
- fos.close();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
设置自己的状态信息
- private void testSetInfo(XMPPConnection conn) throws Exception {
- VCard vCard = new VCard();
- vCard.load(conn);
- vCard.setEmailHome("admin@126.com");
- vCard.setAddressFieldWork("POSTAL", "汇宝大厦");
-
- vCard.save(conn);
-
- Presence p = new Presence(Type.available);
- p.setTo("ly@192.168.1.100");
-
- p.setStatus("我的心情");
-
- conn.sendPacket(p);
- }
监听好友的状态
- private void testSetRosterListener(XMPPConnection conn) throws Exception {
- Roster r = conn.getRoster();
- r.createEntry("ly@192.168.1.100", "昵称", null);
- r.addRosterListener(new RosterListener() {
-
- @Override
- public void presenceChanged(Presence presence) {
-
- System.out.println("presenceChanged");
- }
-
- @Override
- public void entriesUpdated(Collection<String> addresses) {
-
- System.out.println("entriesUpdated");
- }
-
- @Override
- public void entriesDeleted(Collection<String> addresses) {
-
- System.out.println("entriesDeleted");
- }
-
- @Override
- public void entriesAdded(Collection<String> addresses) {
-
- System.out.println("entriesAdded");
- }
- });
- }
监听好友的输入状态
- private void testGetExtention(XMPPConnection conn) throws Exception {
- Chat chat = ChatManager.getInstanceFor(conn).createChat("ly@192.168.1.100", new MessageListener() {
-
- @Override
- public void processMessage(Chat chat, Message message) {
-
- PacketExtension pe = message.getExtension("http://jabber.org/protocol/chatstates");
- switch (pe.getElementName()) {
- case "composing":
- System.out.println("正在输入......");
- break;
- case "paused":
- System.out.println("正在冥想......");
- break;
- case "active":
- System.out.println("对方已发送。");
- break;
- case "gone":
- System.out.println("对话框已被关闭。");
- break;
- default:
- break;
- }
- }
- });
- Message msg = new Message();
- msg.addExtension(new ChatStateExtension(ChatState.gone));
- msg.setBody("hello world");
- chat.sendMessage(msg);
- }
增加聊天室进行多人聊天
- private MultiUserChat multiUserChat;
- private void testMutiUserChat(XMPPConnection conn) throws Exception {
- MultiUserChat.addInvitationListener(conn, new InvitationListener() {
-
- @Override
- public void invitationReceived(XMPPConnection conn, String room, String inviter, String reason, String password, Message message) {
- StringBuilder sb = new StringBuilder();
- sb.append("房间号 : ").append(room);
- sb.append("\n邀请者 : ").append(inviter);
- sb.append("\n理由 : ").append(reason);
- sb.append("\n密码 : ").append(password);
- sb.append("\n消息 : ").append(message);
- System.out.println(sb);
- multiUserChat = new MultiUserChat(conn, room);
- try {
- multiUserChat.join("admin", password);
- } catch (XMPPErrorException e) {
-
- e.printStackTrace();
- } catch (SmackException e) {
-
- e.printStackTrace();
- }
- multiUserChat.addMessageListener(new PacketListener() {
-
- @Override
- public void processPacket(Packet packet) throws NotConnectedException {
- Message msg = (Message) packet;
- System.out.println(msg.getBody());
- }
- });
- }
- });
- while(true) {
- try {
- Thread.sleep(500);
- if(multiUserChat == null)
- continue;
-
-
-
-
-
-
-
-
-
- Message msg = new Message();
-
- msg.setTo("a@conference.192.168.1.100");
- msg.setType(Message.Type.groupchat);
- msg.setThread(Thread.currentThread().getId() + "");
- msg.setBody("hello");
- multiUserChat.sendMessage(msg);
- break;
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (NotConnectedException e) {
- e.printStackTrace();
- } catch (XMPPException e) {
- e.printStackTrace();
- }
- }
- }
-
发送和接收文件
- private void testSendFile(XMPPConnection conn) throws Exception {
-
- FileTransferManager ftm = new FileTransferManager(conn);
- ftm.addFileTransferListener(new FileTransferListener() {
-
- @Override
- public void fileTransferRequest(FileTransferRequest request) {
- System.out.println(request.getFileName());
- IncomingFileTransfer inComingFileTransfer = request.accept();
- try {
-
- File file = new File("D://" + request.getFileName());
- inComingFileTransfer.recieveFile(file);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
-
-
-
- OutgoingFileTransfer oft = ftm.createOutgoingFileTransfer("admin@192.168.1.100/潘迪安");
- File file = new File("D://time.jpg");
- oft.sendFile(file, "图片");
- System.out.println(oft.isDone());
- }
创建多人聊天室
- private void testCreateRoom(XMPPConnection conn) throws Exception {
- while(true) {
- if(conn != null)
- break;
- }
-
- MultiUserChat muc = new MultiUserChat(conn, "ly@conference.192.168.1.100");
-
- muc.create("real_admin");
- Form form = muc.getConfigurationForm();
- Form submitForm = form.createAnswerForm();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- muc.sendConfigurationForm(submitForm);
-
- muc.addInvitationRejectionListener(new InvitationRejectionListener() {
-
- @Override
- public void invitationDeclined(String invitee, String reason) {
- System.out.println(invitee + " : " + reason);
- }
- });
- muc.invite("yy@192.168.1.100", "ly_room");
- }
管理房间
- <pre name="code" class="java">private void testManageRoom(XMPPConnection conn) throws Exception {
- testCreateRoom(conn);
- MultiUserChat muc = new MultiUserChat(conn, "ly@conference.192.168.1.100");
-
-
-
-
-
-
-
-
-
-
- muc.revokeVoice("yy");
-
- }
注冊
- private void testRegister(XMPPConnection conn) throws Exception {
-
- Registration r = new Registration();
- Map<String, String> attributes = new HashMap<String, String>();
- attributes.put("username", "newuser");
- attributes.put("password", "0");
- attributes.put("email", "new00@126.com");
- attributes.put("name", "name@192.168.1.100");
-
- r.setType(IQ.Type.SET);
- r.setAttributes(attributes);
-
- PacketFilter packetFilter = new AndFilter(new PacketIDFilter(r.getPacketID()), new PacketTypeFilter(IQ.class));
- PacketCollector collector = conn.createPacketCollector(packetFilter);
- System.out.println(r);
- conn.sendPacket(r);
- IQ result = (IQ) collector.nextResult();
- if(result == null) {
- System.out.println("server没有返回不论什么信息");
- } else {
- switch (result.getType().toString()) {
- case "result":
- System.out.println("注冊成功");
- break;
- case "error":
- if(result.getError().toString().equalsIgnoreCase("conflict"))
- System.out.println("用户名称已存在");
- else
- System.out.println("注冊失败");
- break;
- default:
- break;
- }
- }
- }
管理账号password
- private void testModifyPwd(XMPPConnection conn) throws Exception {
-
- AccountManager am = AccountManager.getInstance(conn);
- Collection<String> c = am.getAccountAttributes();
- for(String s : c) {
- System.out.println(s);
- }
-
-
-
-
-
-
-
-
- am.getAccountAttribute("username");
- am.createAccount("newUser", "0");
- am.changePassword("00");
- }
至于细节,中遇到,我在程序代码描述
参考博客:
http://blog.csdn.net/shimiso/article/details/11225873