首先xmpp server需要安装好配置并启动,这里只是实现简单的文本发送和文件发送,接受需要用xmpp client来接收
下载地址:http://www./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)根据需求引用这些jar
下面是一个简单的java代码,这是做简单测试,没有详细优化过(测试时发现个小问题:发文件需要对方加你为好友后,你发文件的时候才会显示,不加好友的话发送时是接收方有提示但是没看到发送过来的文件,如果是发生文本消息则没有这个问题)
首先spark为接收方登入
然后执行下面的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;
}
//发送文件
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);
}
}
//发送文本
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........!");
}
}
|