在文章开始,请你了解和熟悉openfire方面的相关知识,这样对你理解下面代码以及下面代码的用途有很好的了解。同时,你可能需要安装一个简单的CS聊天工具,来测试你的代码是否成功的在openfire服务器上建立会话链接,并成功的向在线用户发送聊天消息。

必须了解:http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html

http://www.cnblogs.com/hoojo/archive/2012/05/13/2498151.html (非windows 系统)

可选:http://www.cnblogs.com/hoojo/archive/2012/05/17/2506845.html

http://www.cnblogs.com/hoojo/archive/2012/06/18/2553975.html

聊天软件Spark,用于测试聊天消息发送是否成功,下载地址:http://www.igniterealtime.org/downloads/download-landing.jsp?file=spark/spark_2_6_3.exe

然后你需要添加smack相关的jar包

smack.jar
smackx.jar

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

代码中还用到了junit,junit jar下载地址:http://ebr.springsource.com/repository/app/bundle/version/download?name=com.springsource.org.junit&version=4.8.2&type=binary

下面开始代码部分

package com.hoo.smack;

 

import java.util.Collection;

import java.util.Iterator;

import javax.net.SocketFactory;

import org.jivesoftware.smack.AccountManager;

import org.jivesoftware.smack.Chat;

import org.jivesoftware.smack.ChatManager;

import org.jivesoftware.smack.Connection;

import org.jivesoftware.smack.ConnectionConfiguration;

import org.jivesoftware.smack.MessageListener;

import org.jivesoftware.smack.Roster;

import org.jivesoftware.smack.RosterEntry;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import org.jivesoftware.smack.packet.Message;

import org.jivesoftware.smack.packet.Presence;

import org.jivesoftware.smack.packet.Session;

import org.jivesoftware.smack.packet.Message.Type;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

 

/**

 * <b>function:</b> 利用Smack框架完成 XMPP 协议通信

 * @author hoojo

 * @createDate 2012-5-22 上午10:28:18

 * @file ConnectionServerTest.java

 * @package com.hoo.smack.conn

 * @project jwchat

 * @blog http://blog.csdn.net/IBM_hoojo

 * @email hoojo_@126.com

 * @version 1.0

 */

public class SmackXMPPTest {

 

    private Connection connection;

    private ConnectionConfiguration config;

    /** openfire服务器address */

    private final static String server = "192.168.8.32";

    

    private final void fail(Object o) {

        if (o != null) {

            System.out.println(o);

        }

    }

    

    private final void fail(Object o, Object... args) {

        if (o != null && args != null && args.length > 0) {

            String s = o.toString();

            for (int i = 0; i < args.length; i++) {

                String item = args[i] == null ? "" : args[i].toString();

                if (s.contains("{" + i + "}")) {

                    s = s.replace("{" + i + "}", item);

                } else {

                    s += " " + item;

                }

            }

            System.out.println(s);

        }

    }

    

    /**

     * <b>function:</b> 初始Smack对openfire服务器链接的基本配置

     * @author hoojo

     * @createDate 2012-6-25 下午04:06:42

     */

    @Before

    public void init() {

        try {

            //connection = new XMPPConnection(server);

            //connection.connect();

            /** 5222是openfire服务器默认的通信端口,你可以登录http://192.168.8.32:9090/到管理员控制台查看客户端到服务器端口 */

            config = new ConnectionConfiguration(server, 5222);

            

            /** 是否启用压缩 */ 

            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();

        }

        fail(connection);

        fail(connection.getConnectionID());

    }

    

    @After

    public void destory() {

        if (connection != null) {

            connection.disconnect();

            connection = null;

        }

    }

    

    /**

     * <b>function:</b> ConnectionConfiguration 的基本配置相关信息

     * @author hoojo

     * @createDate 2012-6-25 下午04:11:25

     */

    @Test

    public void testConfig() {

        fail("PKCS11Library: " + config.getPKCS11Library());

        fail("ServiceName: {0}", config.getServiceName());

        // ssl证书密码

        fail("TruststorePassword: {0}", config.getTruststorePassword());

        fail("TruststorePath: {0}", config.getTruststorePath());

        fail("TruststoreType: {0}", config.getTruststoreType());

        

        SocketFactory socketFactory = config.getSocketFactory();

        fail("SocketFactory: {0}", socketFactory);

        /*try {

            fail("createSocket: {0}", socketFactory.createSocket("localhost", 3333));

        } catch (IOException e) {

            e.printStackTrace();

        }*/

    }

    

    /**

     * <b>function:</b> Connection 基本方法信息

     * @author hoojo

     * @createDate 2012-6-25 下午04:12:04

     */

    @Test

    public void testConnection() {

        /** 用户管理 */

        AccountManager accountManager = connection.getAccountManager();

        for (String attr : accountManager.getAccountAttributes()) {

            fail("AccountAttribute: {0}", attr);

        }

        fail("AccountInstructions: {0}", accountManager.getAccountInstructions());

        /** 是否链接 */

        fail("isConnected:", connection.isConnected());

        fail("isAnonymous:", connection.isAnonymous());

        /** 是否有权限 */

        fail("isAuthenticated:", connection.isAuthenticated());

        fail("isSecureConnection:", connection.isSecureConnection());

        /** 是否使用压缩 */

        fail("isUsingCompression:", connection.isUsingCompression());

    }

    

    /**

     * <b>function:</b> 用户管理器

     * @author hoojo

     * @createDate 2012-6-25 下午04:22:31

     */

    @Test

    public void testAccountManager() {

        AccountManager accountManager = connection.getAccountManager();

        for (String attr : accountManager.getAccountAttributes()) {

            fail("AccountAttribute: {0}", attr);

        }

        fail("AccountInstructions: {0}", accountManager.getAccountInstructions());

        

        fail("supportsAccountCreation: {0}", accountManager.supportsAccountCreation());

        try {

            /** 创建一个用户boy,密码为boy;你可以在管理员控制台页面http://192.168.8.32:9090/user-summary.jsp查看用户/组的相关信息,来查看是否成功创建用户 */

            accountManager.createAccount("boy", "boy");

            /** 修改密码 */

            accountManager.changePassword("abc");

        } catch (XMPPException e) {

            e.printStackTrace();

        }

    }

    

    @Test

    public void testUser() {

        try {

            /** 用户登陆,用户名、密码 */

            connection.login("hoojo", "hoojo");

        } catch (XMPPException e) {

            e.printStackTrace();

        }

        /** 获取当前登陆用户 */

        fail("User:", connection.getUser());

        

        /** 所有用户组 */

        Roster roster = connection.getRoster();

        

        /** 好友用户组,你可以用Spark添加用户好友,这样这里就可以查询到相关的数据 */

        Collection<RosterEntry> rosterEntiry = roster.getEntries();

        Iterator<RosterEntry> iter = rosterEntiry.iterator();

        while (iter.hasNext()) {

            RosterEntry entry = iter.next();

            fail("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", entry.getGroups(), entry.getName(), entry.getStatus(), entry.getType(), entry);

        }

        

        fail("-------------------------------");

        /** 未处理、验证好友,添加过的好友,没有得到对方同意 */

        Collection<RosterEntry> unfiledEntries = roster.getUnfiledEntries();

        iter = unfiledEntries.iterator();

        while (iter.hasNext()) {

            RosterEntry entry = iter.next();

            fail("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", entry.getGroups(), entry.getName(), entry.getStatus(), entry.getType(), entry);

        }

    }

    

    @Test

    @SuppressWarnings("static-access")

    public void testPacket() {

        try {

            connection.login("hoojo", "hoojo");

        } catch (XMPPException e) {

            e.printStackTrace();

        }

        

        //Packet packet = new Data(new DataPacketExtension("jojo@" + server, 2, "this is a message"));

        //connection.sendPacket(packet);

        

        /** 更改用户状态,available=true表示在线,false表示离线,status状态签名;当你登陆后,在Spark客户端软件中就可以看到你登陆的状态 */

        Presence presence = new Presence(Presence.Type.available);

        presence.setStatus("Q我吧");

        connection.sendPacket(presence);

        

        Session session = new Session();

        String sessid = session.nextID();

        connection.sendPacket(session);

        /** 向jojo@192.168.8.32 发送聊天消息,此时你需要用Spark软件登陆jojo这个用户,

         * 这样代码就可以向jojo这个用户发送聊天消息,Spark登陆的jojo用户就可以接收到消息

         **/

        /** Type.chat 表示聊天,groupchat多人聊天,error错误,headline在线用户; */

        Message message = new Message("jojo@" + server, Type.chat);

        //Message message = new Message(sessid, Type.chat);

        message.setBody("h!~ jojo, I'am is hoojo!");

        connection.sendPacket(message);

        

        try {

            Thread.sleep(1);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    

    /**

     * <b>function:</b> 测试聊天消息管理类

     * @author hoojo

     * @createDate 2012-6-25 下午05:03:23

     */

    @Test

    public void testChatManager() {

        /** 设置状态 */

        try {

            connection.login("hoojo", "hoojo");

        } catch (XMPPException e) {

            e.printStackTrace();

        }

        

        /** 设置状态 */

        Presence presence = new Presence(Presence.Type.available);

        presence.setStatus("Q我吧");

        connection.sendPacket(presence);

        

        /** 获取当前登陆用户的聊天管理器 */

        ChatManager chatManager = connection.getChatManager();

        /** 为指定用户创建一个chat,MyMessageListeners用于监听对方发过来的消息  */

        Chat chat = chatManager.createChat("jojo@" + server, new MyMessageListeners());

        try {

            /** 发送消息 */

            chat.sendMessage("h!~ jojo……");

            

            /** 用message对象发送消息 */

            Message message = new Message();

            message.setBody("message");

            message.setProperty("color", "red");

            chat.sendMessage(message);

        } catch (XMPPException e) {

            e.printStackTrace();

        }

        try {

            Thread.sleep(1000 * 1000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    

    /**

     * <b>function:</b> 消息监听器,用户监听对方发送的消息,也可以想对方发送消息

     * @author hoojo

     * @createDate 2012-6-25 下午05:05:31

     * @file SmackXMPPTest.java

     * @package com.hoo.smack

     * @project jwchat

     * @blog http://blog.csdn.net/IBM_hoojo

     * @email hoojo_@126.com

     * @version 1.0

     */

    class MyMessageListeners implements MessageListener {

        public void processMessage(Chat chat, Message message) {

            try {

                /** 发送消息 */

                chat.sendMessage("dingding……" + message.getBody());

            } catch (XMPPException e) {

                e.printStackTrace();

            }

            /** 接收消息 */

            fail("From: {0}, To: {1}, Type: {2}, Sub: {3}", message.getFrom(), message.getTo(), message.getType(), message.toXML());

            /*Collection<Body> bodys =  message.getBodies();

            for (Body body : bodys) {

                fail("bodies[{0}]", body.getMessage());

            }

            //fail(message.getLanguage());

            //fail(message.getThread());

            //fail(message.getXmlns());*/

            fail("body: ", message.getBody());

        }

    }

}

本文出自: http://www.cnblogs.com/hoojo/archive/2012/06/25/2561576.html

Smack 结合 Openfire服务器,建立IM通信,发送聊天消息的更多相关文章

  1. spark结合 Openfire服务器,发送聊天消息

    1.下载OpenFire服务器,进行安装,参考http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html 2.程序运行客户端:下载客户端代 ...

  2. XMPP即时通讯协议使用(四)——Openfire服务器源码编译与添加消息记录保存

    下载Openfire源码 下载地址:https://www.igniterealtime.org/downloads/index.jsp,当前最新版本为:4.2.3 Eclipse上部署Openfir ...

  3. 即时通信系统中如何实现:聊天消息加密,让通信更安全? 【低调赠送:QQ高仿版GG 4.5 最新源码】

    加密重要的通信消息,是一个常见的需求.在一些政府部门的即时通信软件中(如税务系统),对聊天消息进行加密是非常重要的一个功能,因为谈话中可能会涉及到机密的数据.我在最新的GG 4.5中,增加了对聊天消息 ...

  4. 即时通信系统中实现聊天消息加密,让通信更安全【低调赠送:C#开源即时通讯系统(支持广域网)——GGTalk4.5 最新源码】

    在即时通讯系统(IM)中,加密重要的通信消息,是一个常见的需求.尤其在一些政府部门的即时通信软件中(如税务系统),对即时聊天消息进行加密是非常重要的一个功能,因为谈话中可能会涉及到机密的数据.我在最新 ...

  5. (转)基于即时通信和LBS技术的位置感知服务(三):搭建Openfire服务器+测试2款IM客户端

    主要包含4个章节: 1. Java 领域的即时通信的解决方案 2. 搭建 Openfire 服务器 3. 使用客户端测试我们搭建的 Openfire 服务器 4. Smack 和 ASmack 一.J ...

  6. 本地Git与GitHub服务器建立连接(SSH方式通信)

    简介 Git是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. github是一个基于git的代码托管平台,付费用户可以建私人仓库,我们一般的免费用户只能使用公共仓库,也就是代码要 ...

  7. 基于XMPP协议(openfire服务器)的消息推送实现

    转自:http://blog.csdn.net/nomousewch/article/details/8088277 最近好像有不少朋友关注Android客户端消息推送的实现,我在之前的项目中用到过J ...

  8. Web浏览器与Web服务器之间的通信过程

     HTTP通信机制是在一次完整的HTTP通信过程中,Web浏览器与Web服务器之间将完成下列7个步骤:1:建立TCP连接 在HTTP工作开始之前,Web浏览器首先要通过网络与Web服务器建立连接,该连 ...

  9. 如何使用HTML5的WebSocket实现网页与服务器的双工通信(二)

    本系列服务端双工通信包括两种实现方式:一.使用Socket构建:二.使用WCF构建.本文为使用WCF构建服务端的双工通信,客户端同样使用Html5的WebSocket技术进行调用. 一.创建WCF服务 ...

随机推荐

  1. Three.js 类的粗略总结和实现

    类 1.Cameras 照相机,包括很多种类型的摄像机类,包括正交类型和投影类型的摄像机 2.Core 核心对象 3.Lights 光照,包括点光,环境光,镜面光等等 4.Loaders 专门用来加载 ...

  2. maven里如何根据不同的environment打包

    一个项目里总会有很多配置文件.而且一般都会有多套环境.开发的.测试的.正式的.而在这些不同的环境这些配置的值都会不一样.比如mail的配置.服务的url配置这些都是很常见的.所以在打包的时候就要根据e ...

  3. 内核升极2.6.18 升级到 2.6.32 装systemtap 原创

    系统: redhat serever 5.3  linux 2.6.18 现在要升级到 LINUX 内核 2.6.32 安装步骤: 1.下载装源代码: https://www.kernel.org/ ...

  4. Linux shell命令中expr

    在Linux shell命令中expr虽然不是很起眼,但是它的作用是非常大的!到目前为止,我个人看来最大的作用就是两个——四则运算和字符串的操作. 先说四则运算,在Shell中四则运算不能简简单单的加 ...

  5. hdu 4647 Another Graph Game,想到了就是水题了。。

    题目是给一个无向图,其中每个节点都有点权,边也有边权,然后就有2个小朋友开始做游戏了ALICE &BOB 游戏规定ALICE 先行动然后是BOB,然后依次轮流行动,行动时可以任意选取一个节点并 ...

  6. C++空类产生哪些成员函数 || C++类可以自动生成的6个成员函数

    class Empty {     public:     Empty(); // 缺省构造函数     Empty( const Empty& ); // 拷贝构造函数     ~Empty ...

  7. Lucene新版本号对ConjunctionScorer的优化

    Lucene 4.0版本号的DocIdSetIterator中没有cost方法,而4.7.0则有这种方法,表示遍历整个DocIdSet的代价,对于DocsEnum就是其长度了,对于Scorer就能够是 ...

  8. datagrid在MVC中的运用08-实现Master-Detail(使用子datagrid)

    本文主要通过一个子datagrid来实现主次表.谢谢Kevin的博文. 代码部分与http://www.cnblogs.com/darrenji/p/3576258.html相似,这里只列出不一样的地 ...

  9. MySQL面试题集锦

    1. 如何设计一个高并发的系统 ① 数据库的优化,包括合理的事务隔离级别.SQL语句优化.索引的优化 ② 使用缓存,尽量减少数据库 IO ③ 分布式数据库.分布式缓存 ④ 服务器的负载均衡 2. 锁的 ...

  10. 更改Mantis的logo

    1 准备好自己的logo,例如准备的logo为zhaoxiyu.gif.zxy.gif 2 把上面的两个logo存放到C:/mantis-1.0.0a3/images 3 打开C:/mantis-1. ...