在文章开始,请你了解和熟悉openfire方面的相关知识,这样对你理解下面代码以及下面代码的用途有很好的了解。同时,你可能需要安装一个简单的CS聊天工具,来测试你的代码是否成功的在openfire服务器上建立会话链接,并成功的向在线用户发送聊天消息。
聊天软件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
001 | package com.hoo.smack; |
002 | |
003 | import java.util.Collection; |
004 | import java.util.Iterator; |
005 | import javax.net.SocketFactory; |
006 | import org.jivesoftware.smack.AccountManager; |
007 | import org.jivesoftware.smack.Chat; |
008 | import org.jivesoftware.smack.ChatManager; |
009 | import org.jivesoftware.smack.Connection; |
010 | import org.jivesoftware.smack.ConnectionConfiguration; |
011 | import org.jivesoftware.smack.MessageListener; |
012 | import org.jivesoftware.smack.Roster; |
013 | import org.jivesoftware.smack.RosterEntry; |
014 | import org.jivesoftware.smack.XMPPConnection; |
015 | import org.jivesoftware.smack.XMPPException; |
016 | import org.jivesoftware.smack.packet.Message; |
017 | import org.jivesoftware.smack.packet.Presence; |
018 | import org.jivesoftware.smack.packet.Session; |
019 | import org.jivesoftware.smack.packet.Message.Type; |
020 | import org.junit.After; |
021 | import org.junit.Before; |
022 | import org.junit.Test; |
023 | |
024 | /** |
025 | * 利用Smack框架完成 XMPP 协议通信 |
026 | */ |
027 | public class SmackXMPPTest { |
028 | |
029 | private Connection connection; |
030 | private ConnectionConfiguration config; |
031 | /** openfire服务器address */ |
032 | private final static String server = "192.168.8.32" ; |
033 | |
034 | private final void fail(Object o) { |
035 | if (o != null ) { |
036 | System.out.println(o); |
037 | } |
038 | } |
039 | |
040 | private final void fail(Object o, Object... args) { |
041 | if (o != null && args != null && args.length > 0 ) { |
042 | String s = o.toString(); |
043 | for ( int i = 0 ; i < args.length; i++) { |
044 | String item = args[i] == null ? "" : args[i].toString(); |
045 | if (s.contains( "{" + i + "}" )) { |
046 | s = s.replace( "{" + i + "}" , item); |
047 | } else { |
048 | s += " " + item; |
049 | } |
050 | } |
051 | System.out.println(s); |
052 | } |
053 | } |
054 | |
055 | /** |
056 | * 初始Smack对openfire服务器链接的基本配置 |
057 | */ |
058 | @Before |
059 | public void init() { |
060 | try { |
061 | //connection = new XMPPConnection(server); |
062 | //connection.connect(); |
063 | /** 5222是openfire服务器默认的通信端口,你可以登录http://192.168.8.32:9090/到管理员控制台查看客户端到服务器端口 */ |
064 | config = new ConnectionConfiguration(server, 5222 ); |
065 | |
066 | /** 是否启用压缩 */ |
067 | config.setCompressionEnabled( true ); |
068 | /** 是否启用安全验证 */ |
069 | config.setSASLAuthenticationEnabled( true ); |
070 | /** 是否启用调试 */ |
071 | config.setDebuggerEnabled( false ); |
072 | //config.setReconnectionAllowed(true); |
073 | //config.setRosterLoadedAtLogin(true); |
074 | |
075 | /** 创建connection链接 */ |
076 | connection = new XMPPConnection(config); |
077 | /** 建立连接 */ |
078 | connection.connect(); |
079 | } catch (XMPPException e) { |
080 | e.printStackTrace(); |
081 | } |
082 | fail(connection); |
083 | fail(connection.getConnectionID()); |
084 | } |
085 | |
086 | @After |
087 | public void destory() { |
088 | if (connection != null ) { |
089 | connection.disconnect(); |
090 | connection = null ; |
091 | } |
092 | } |
093 | |
094 | /** |
095 | * ConnectionConfiguration 的基本配置相关信息 |
096 | */ |
097 | @Test |
098 | public void testConfig() { |
099 | fail( "PKCS11Library: " + config.getPKCS11Library()); |
100 | fail( "ServiceName: {0}" , config.getServiceName()); |
101 | // ssl证书密码 |
102 | fail( "TruststorePassword: {0}" , config.getTruststorePassword()); |
103 | fail( "TruststorePath: {0}" , config.getTruststorePath()); |
104 | fail( "TruststoreType: {0}" , config.getTruststoreType()); |
105 | |
106 | SocketFactory socketFactory = config.getSocketFactory(); |
107 | fail( "SocketFactory: {0}" , socketFactory); |
108 | /*try { |
109 | fail("createSocket: {0}", socketFactory.createSocket("localhost", 3333)); |
110 | } catch (IOException e) { |
111 | e.printStackTrace(); |
112 | }*/ |
113 | } |
114 | |
115 | /** |
116 | * Connection 基本方法信息 |
117 | */ |
118 | @Test |
119 | public void testConnection() { |
120 | /** 用户管理 */ |
121 | AccountManager accountManager = connection.getAccountManager(); |
122 | for (String attr : accountManager.getAccountAttributes()) { |
123 | fail("AccountAttribute: {0}", attr); |
124 | } |
125 | fail("AccountInstructions: {0}", accountManager.getAccountInstructions()); |
126 | /** 是否链接 */ |
127 | fail("isConnected:", connection.isConnected()); |
128 | fail("isAnonymous:", connection.isAnonymous()); |
129 | /** 是否有权限 */ |
130 | fail("isAuthenticated:", connection.isAuthenticated()); |
131 | fail("isSecureConnection:", connection.isSecureConnection()); |
132 | /** 是否使用压缩 */ |
133 | fail("isUsingCompression:", connection.isUsingCompression()); |
134 | } |
135 | |
136 | /** |
137 | * 用户管理器 |
138 | */ |
139 | @Test |
140 | public void testAccountManager() { |
141 | AccountManager accountManager = connection.getAccountManager(); |
142 | for (String attr : accountManager.getAccountAttributes()) { |
143 | fail("AccountAttribute: {0}", attr); |
144 | } |
145 | fail("AccountInstructions: {0}", accountManager.getAccountInstructions()); |
146 | |
147 | fail("supportsAccountCreation: {0}", accountManager.supportsAccountCreation()); |
148 | try { |
149 | /** 创建一个用户boy,密码为boy;你可以在管理员控制台页面http://192.168.8.32:9090/user-summary.jsp查看用户/组的相关信息,来查看是否成功创建用户 */ |
150 | accountManager.createAccount("boy", "boy"); |
151 | /** 修改密码 */ |
152 | accountManager.changePassword("abc"); |
153 | } catch (XMPPException e) { |
154 | e.printStackTrace(); |
155 | } |
156 | } |
157 | |
158 | @Test |
159 | public void testUser() { |
160 | try { |
161 | /** 用户登陆,用户名、密码 */ |
162 | connection.login("hoojo", "hoojo"); |
163 | } catch (XMPPException e) { |
164 | e.printStackTrace(); |
165 | } |
166 | /** 获取当前登陆用户 */ |
167 | fail("User:", connection.getUser()); |
168 | |
169 | /** 所有用户组 */ |
170 | Roster roster = connection.getRoster(); |
171 | |
172 | /** 好友用户组,你可以用Spark添加用户好友,这样这里就可以查询到相关的数据 */ |
173 | Collection<RosterEntry> rosterEntiry = roster.getEntries(); |
174 | Iterator<RosterEntry> iter = rosterEntiry.iterator(); |
175 | while (iter.hasNext()) { |
176 | RosterEntry entry = iter.next(); |
177 | fail("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", entry.getGroups(), entry.getName(), entry.getStatus(), entry.getType(), entry); |
178 | } |
179 | |
180 | fail("-------------------------------"); |
181 | /** 未处理、验证好友,添加过的好友,没有得到对方同意 */ |
182 | Collection<RosterEntry> unfiledEntries = roster.getUnfiledEntries(); |
183 | iter = unfiledEntries.iterator(); |
184 | while (iter.hasNext()) { |
185 | RosterEntry entry = iter.next(); |
186 | fail("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", entry.getGroups(), entry.getName(), entry.getStatus(), entry.getType(), entry); |
187 | } |
188 | } |
189 | |
190 | @Test |
191 | @SuppressWarnings("static-access") |
192 | public void testPacket() { |
193 | try { |
194 | connection.login("hoojo", "hoojo"); |
195 | } catch (XMPPException e) { |
196 | e.printStackTrace(); |
197 | } |
198 | |
199 | //Packet packet = new Data(new DataPacketExtension("jojo@" + server, 2, "this is a message")); |
200 | //connection.sendPacket(packet); |
201 | |
202 | /** 更改用户状态,available=true表示在线,false表示离线,status状态签名;当你登陆后,在Spark客户端软件中就可以看到你登陆的状态 */ |
203 | Presence presence = new Presence(Presence.Type.available); |
204 | presence.setStatus("Q我吧"); |
205 | connection.sendPacket(presence); |
206 | |
207 | Session session = new Session(); |
208 | String sessid = session.nextID(); |
209 | connection.sendPacket(session); |
210 | /** 向jojo@192.168.8.32 发送聊天消息,此时你需要用Spark软件登陆jojo这个用户, |
211 | * 这样代码就可以向jojo这个用户发送聊天消息,Spark登陆的jojo用户就可以接收到消息 |
212 | **/ |
213 | /** Type.chat 表示聊天,groupchat多人聊天,error错误,headline在线用户; */ |
214 | Message message = new Message("jojo@" + server, Type.chat); |
215 | //Message message = new Message(sessid, Type.chat); |
216 | message.setBody("h!~ jojo, I'am is hoojo!"); |
217 | connection.sendPacket(message); |
218 | |
219 | try { |
220 | Thread.sleep(1); |
221 | } catch (InterruptedException e) { |
222 | e.printStackTrace(); |
223 | } |
224 | } |
225 | |
226 | /** |
227 | * 测试聊天消息管理类 |
228 | */ |
229 | @Test |
230 | public void testChatManager() { |
231 | /** 设置状态 */ |
232 | try { |
233 | connection.login("hoojo", "hoojo"); |
234 | } catch (XMPPException e) { |
235 | e.printStackTrace(); |
236 | } |
237 | |
238 | /** 设置状态 */ |
239 | Presence presence = new Presence(Presence.Type.available); |
240 | presence.setStatus("Q我吧"); |
241 | connection.sendPacket(presence); |
242 | |
243 | /** 获取当前登陆用户的聊天管理器 */ |
244 | ChatManager chatManager = connection.getChatManager(); |
245 | /** 为指定用户创建一个chat,MyMessageListeners用于监听对方发过来的消息 */ |
246 | Chat chat = chatManager.createChat("jojo@" + server, new MyMessageListeners()); |
247 | try { |
248 | /** 发送消息 */ |
249 | chat.sendMessage("h!~ jojo……"); |
250 | |
251 | /** 用message对象发送消息 */ |
252 | Message message = new Message(); |
253 | message.setBody("message"); |
254 | message.setProperty("color", "red"); |
255 | chat.sendMessage(message); |
256 | } catch (XMPPException e) { |
257 | e.printStackTrace(); |
258 | } |
259 | try { |
260 | Thread.sleep(1000 * 1000); |
261 | } catch (InterruptedException e) { |
262 | e.printStackTrace(); |
263 | } |
264 | } |
265 | |
266 | /** |
267 | * 消息监听器,用户监听对方发送的消息,也可以想对方发送消息 |
268 | */ |
269 | class MyMessageListeners implements MessageListener { |
270 | public void processMessage(Chat chat, Message message) { |
271 | try { |
272 | /** 发送消息 */ |
273 | chat.sendMessage("dingding……" + message.getBody()); |
274 | } catch (XMPPException e) { |
275 | e.printStackTrace(); |
276 | } |
277 | /** 接收消息 */ |
278 | fail("From: {0}, To: {1}, Type: {2}, Sub: {3}", message.getFrom(), message.getTo(), message.getType(), message.toXML()); |
279 | /*Collection<Body> bodys = message.getBodies(); |
280 | for (Body body : bodys) { |
281 | fail("bodies[{0}]", body.getMessage()); |
282 | } |
283 | //fail(message.getLanguage()); |
284 | //fail(message.getThread()); |
285 | //fail(message.getXmlns());*/ |
286 | fail( "body: " , message.getBody()); |
287 | } |
288 | } |
289 | } |
好了,这些都是smack的基本功能。
原文地址:http://www.blogjava.net/hoojo/archive/2012/06/25/381445.html