首先xmpp server需要安裝好配置并啟動(dòng),這里只是實(shí)現(xiàn)簡(jiǎn)單的文本發(fā)送和文件發(fā)送,接受需要用xmpp client來(lái)接收
下載地址:http://www.igniterealtime.org/downloads/index.jsp
xmpp server(openfire)
xmpp client(spark)
Java XMPP client library(smack)
smack下載完后,壓縮包里面有例子、api、和jar(smack.jar、smackx.jar、smackx-debug.jar、smackx-jingle.jar)根據(jù)需求引用這些jar
下面是一個(gè)簡(jiǎn)單的java代碼,這是做簡(jiǎn)單測(cè)試,沒有詳細(xì)優(yōu)化過(guò)(測(cè)試時(shí)發(fā)現(xiàn)個(gè)小問題:發(fā)文件需要對(duì)方加你為好友后,你發(fā)文件的時(shí)候才會(huì)顯示,不加好友的話發(fā)送時(shí)是接收方有提示但是沒看到發(fā)送過(guò)來(lái)的文件,如果是發(fā)生文本消息則沒有這個(gè)問題)
首先spark為接收方登入
然后執(zhí)行下面的java代碼
package com.test.xmpp;
import java.io.File;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
/**
* @author test
*
*/
public class TestXmpp {
/**
* @param args
*/
public static void main(String[] args){
String user = "user@testHost/spark";
String host = "localhost";
int port = 5222;
String username = "test";
String password = "test";
ConnectionConfiguration config = new ConnectionConfiguration(host,port);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(config);
try{
connection.connect();
connection.login(username, password);
sendFile(user,getFile(),connection );
// sendTextMessage(user,connection);
}catch(Exception e){
e.printStackTrace();
}finally{
connection.disconnect();
}
}
public static File getFile(){
File file = new File("D:/test.jpg");
return file;
}
//發(fā)送文件
public static void sendFile(String user,File file,XMPPConnection connection ) throws Exception{
FileTransferManager manager = new FileTransferManager(connection);
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(user);
long timeOut = 1000000;
long sleepMin = 3000;
long spTime = 0;
int rs = 0;
transfer.sendFile(file, "pls re file!");
rs = transfer.getStatus().compareTo(FileTransfer.Status.complete);
while(rs!=0){
rs = transfer.getStatus().compareTo(FileTransfer.Status.complete);
spTime = spTime + sleepMin;
if(spTime>timeOut){return ;}
Thread.sleep(sleepMin);
}
}
//發(fā)送文本
public static void sendTextMessage(String user,XMPPConnection connection) throws Exception{
Chat chat = connection.getChatManager().createChat(user, new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
chat.sendMessage("Hi Test Send Message........!");
}
}
聯(lián)系客服