即時(shí)通訊(Instant Messaging)是目前Internet上最為流行的通訊方式,各種各樣的即時(shí)通訊軟件也層出不窮;服務(wù)提供商也提供了越來越豐富的通訊服務(wù)功能。不容置疑,Internet已經(jīng)成為真正的信息高速公路。從實(shí)際工程應(yīng)用角度出發(fā),以計(jì)算機(jī)網(wǎng)絡(luò)原理為指導(dǎo),結(jié)合當(dāng)前網(wǎng)絡(luò)中的一些常用技術(shù),編程實(shí)現(xiàn)基于C/S架構(gòu)的網(wǎng)絡(luò)聊天工具是切實(shí)可行的。
目前,中國市場上的企業(yè)級(jí)即時(shí)通信工具主要包括:信鴿、視高科技的視高可視協(xié)同辦公平臺(tái)、263EM、群英CC2010、通軟聯(lián)合的GoCom、騰訊公司的RTX、IBM的Lotus Sametime、點(diǎn)擊科技的GKE、中國互聯(lián)網(wǎng)辦公室的imo、中國移動(dòng)的企業(yè)飛信、華夏易聯(lián)的e-Link、擎旗的UcStar等。相對(duì)于個(gè)人即時(shí)通信工具而言,企業(yè)級(jí)即時(shí)通信工具更加強(qiáng)調(diào)安全性、實(shí)用性、穩(wěn)定性和擴(kuò)展性。
本文為大家介紹java Smack整合Openfire服務(wù)器實(shí)現(xiàn)IM即時(shí)通訊聊天功能代碼。
詳細(xì)程序
java Smack整合Openfire服務(wù)器實(shí)現(xiàn)IM即時(shí)通訊聊天功能代碼如下:
[java] view plain copy print?
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;
/**
* 利用Smack框架完成 XMPP 協(xié)議通信
*/
public class SmackXMPPTest {
private Connection connection;
private ConnectionConfiguration config;
/** openfire服務(wù)器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);
}
}
/**
* 初始Smack對(duì)openfire服務(wù)器鏈接的基本配置
*/
@Before
public void init() {
try {
//connection = new XMPPConnection(server);
//connection.connect();
/** 5222是openfire服務(wù)器默認(rèn)的通信端口,你可以登錄http://192.168.8.32:9090/到管理員控制臺(tái)查看客戶端到服務(wù)器端口 */
config = new ConnectionConfiguration(server, 5222);
/** 是否啟用壓縮 */
config.setCompressionEnabled(true);
/** 是否啟用安全驗(yàn)證 */
config.setSASLAuthenticationEnabled(true);
/** 是否啟用調(diào)試 */
config.setDebuggerEnabled(false);
//config.setReconnectionAllowed(true);
//config.setRosterLoadedAtLogin(true);
/** 創(chuàng)建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;
}
}
/**
* ConnectionConfiguration 的基本配置相關(guān)信息
*/
@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(“l(fā)ocalhost”, 3333));
} catch (IOException e) {
e.printStackTrace();
}*/
}
/**
* Connection 基本方法信息
*/
@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());
/** 是否有權(quán)限 */
fail(“isAuthenticated:”, connection.isAuthenticated());
fail(“isSecureConnection:”, connection.isSecureConnection());
/** 是否使用壓縮 */
fail(“isUsingCompression:”, connection.isUsingCompression());
}
/**
* 用戶管理器
*/
@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 {
/** 創(chuàng)建一個(gè)用戶boy,密碼為boy;你可以在管理員控制臺(tái)頁面http://192.168.8.32:9090/user-summary.jsp查看用戶/組的相關(guān)信息,來查看是否成功創(chuàng)建用戶 */
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();
}
/** 獲取當(dāng)前登陸用戶 */
fail(“User:”, connection.getUser());
/** 所有用戶組 */
Roster roster = connection.getRoster();
/** 好友用戶組,你可以用Spark添加用戶好友,這樣這里就可以查詢到相關(guān)的數(shù)據(jù) */
Collection rosterEntiry=“roster.getEntries();
Iterator 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(“-------------------------------”);
/** 未處理、驗(yàn)證好友,添加過的好友,沒有得到對(duì)方同意 */
Collection 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);
/** 更改用戶狀態(tài),available=true表示在線,false表示離線,status狀態(tài)簽名;當(dāng)你登陸后,在Spark客戶端軟件中就可以看到你登陸的狀態(tài) */
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 發(fā)送聊天消息,此時(shí)你需要用Spark軟件登陸jojo這個(gè)用戶,
* 這樣代碼就可以向jojo這個(gè)用戶發(fā)送聊天消息,Spark登陸的jojo用戶就可以接收到消息
**/
/** Type.chat 表示聊天,groupchat多人聊天,error錯(cuò)誤,headline在線用戶; */
Message message = new Message(“jojo@” + server, Type.chat);
//Message message = new Message(sessid, Type.chat);
message.setBody(“h!~ jojo, I‘a(chǎn)m is hoojo!”);
connection.sendPacket(message);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 測(cè)試聊天消息管理類
*/
@Test
public void testChatManager() {
/** 設(shè)置狀態(tài) */
try {
connection.login(“hoojo”, “hoojo”);
} catch (XMPPException e) {
e.printStackTrace();
}
/** 設(shè)置狀態(tài) */
Presence presence = new Presence(Presence.Type.available);
presence.setStatus(“Q我吧”);
connection.sendPacket(presence);
/** 獲取當(dāng)前登陸用戶的聊天管理器 */
ChatManager chatManager = connection.getChatManager();
/** 為指定用戶創(chuàng)建一個(gè)chat,MyMessageListeners用于監(jiān)聽對(duì)方發(fā)過來的消息 */
Chat chat = chatManager.createChat(“jojo@” + server, new MyMessageListeners());
try {
/** 發(fā)送消息 */
chat.sendMessage(“h!~ jojo……”);
/** 用message對(duì)象發(fā)送消息 */
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();
}
}
/**
* 消息監(jiān)聽器,用戶監(jiān)聽對(duì)方發(fā)送的消息,也可以想對(duì)方發(fā)送消息
*/
class MyMessageListeners implements MessageListener {
public void processMessage(Chat chat, Message message) {
try {
/** 發(fā)送消息 */
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 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());
}
}
}
評(píng)論
查看更多