Android asmack openfire接收文件
Posted
技术标签:
【中文标题】Android asmack openfire接收文件【英文标题】:Android asmack openfire receiving file 【发布时间】:2014-04-24 12:13:48 【问题描述】:我正在使用以下代码从另一个用户接收文件
FileTransferManager fm = new FileTransferManager(xmppConnection);
fm.addFileTransferListener(new FileTransferListener()
public void fileTransferRequest(final FileTransferRequest request)
Log.i("XMPPClient", "fileTransferRequest ");
new Thread()
@Override
public void run()
IncomingFileTransfer transfer = request.accept();
Log.i("XMPPClient", "IncomingFileTransfer " + transfer);
File mf = Environment.getExternalStorageDirectory();
File file = new File(mf + "/" + transfer.getFileName());
try
transfer.recieveFile(file);
while(!transfer.isDone())
Log.i("XMPPClient", "while..... ");
try
Thread.sleep(1000L);
catch (Exception e)
Log.e("XMPPClient", e.getMessage());
if (transfer.getStatus().equals(
org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error))
Log.e("ERROR!!! ", transfer.getError() + "");
if (transfer.getException() != null)
transfer.getException().printStackTrace();
catch (Exception e)
Log.e("XMPPClient", e.getMessage());
;
.start();
);
catch (IllegalStateException e)
e.printStackTrace();
我已经在我的应用程序的启动器活动中编写了此代码。此外,在启动器活动中,我编写了代码以在单击按钮时发送文件。我在两个不同的设备上运行这个应用程序,分别是 A 和 B。从 A ,我在按钮单击时发送文件,文件从设备 A 传输。但是设备 B 没有收到该文件,即使它没有显示任何日志消息或任何错误
有什么问题?
【问题讨论】:
这个从 smack 传输的文件很重,我们自己做的。问题是我们必须在服务器(openfire)上启用文件传输,并且在连接之前必须设置 ProviderManager,因为库不加载提供程序。如果我没记错的话,您可以像下面的答案所示手动操作(user3532467),也可以使用 Smackandroid.init(context); 是的openfire使用asmack的文件传输不好,需要自己创建openfire的插件 你能给我任何关于在openfire中创建自己的文件传输插件的提示 @PrabhuM 我也在努力解决这个问题,以通过 openfire 传输文件。你能解决问题吗?如果是的话,那你也愿意和我分享一下细节吗? @Kanchan 我正在使用不同的方法来传输文件。当用户浏览并选择文件时,我只是将文件上传到我们的服务器并将服务器上的文件位置作为普通短信发送给收件人,在收件人设备中我只是从该位置下载文件 【参考方案1】:Asmack 文件传输不好,您应该创建插件以在服务器上上传文件并使用该插件返回一个 url..
插件Servlet看起来像
package org.jivesoftware.openfire.plugin.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.plugin.Fileupload;
/**
*
* @author Jaspreet
*/
public class FileUploadServlet extends HttpServlet
private Fileupload plugin;
private static Logger Log = Logger.getLogger(Fileupload.class);
protected long amountWritten = -1;
private static final int BUFFER_SIZE = 8192;
@Override
public void init(ServletConfig servletConfig) throws ServletException
super.init(servletConfig);
plugin = (Fileupload) XMPPServer.getInstance().getPluginManager().getPlugin("fileupload");
Log.info("File upload plugin" +plugin.getClass());
// Exclude this servlet from requiring the user to login
AuthCheckFilter.addExclude("fileupload/userservice");
Log.info("Fileupload plugin AuthCheckFilter.addExclude" );
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
PrintWriter out = response.getWriter();
try
Log.info("response HttpServletRequest ok");
String name=request.getParameter("name");
String type=request.getParameter("type");
Log.info("type = "+type);
Log.info("name = "+name);
if (type.equals("download"))
Log.info("line 68");
OutputStream outputStream=response.getOutputStream();
FileInputStream fileInputStream=new FileInputStream(Fileupload.directory+"/"+name);
Log.info("line 72 ");
sendFile(response, outputStream, fileInputStream);
Log.info("line 73");
return;
catch (Exception e)
// TODO: handle exception
replyMessage("error", response, out);
Log.error("error while downloading file");
Log.info("error = "+e.getMessage());
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
/* String type = request.getHeader("type_");
String name=request.getHeader("name");
Log.info("type = "+type);
Log.info("name = "+name);
if(type.equals("upload"))*/
PrintWriter out = response.getWriter();
try
Log.info("line 93");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Log.info("line 94");
for (FileItem item : items)
Log.info("line 96");
if (item.isFormField())
Log.info("line 98");
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
else
// Process form file field (input type="file").
Log.info("line 105");
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
Log.info("line 108");
InputStream filecontent = item.getInputStream();
Log.info("line 110");
// InputStream inputStream=(InputStream) request.getAttribute("uploaded");
//InputStream inputStream=request.getInputStream();
File file = new File(Fileupload.directory+"/"+filename);
if(!file.exists())
file.createNewFile();
// File file = new File(filename);
Log.info("line 114");
FileOutputStream fop = new FileOutputStream(file);
Log.info("line 116");
uploadFile(response, fop, filecontent);
Log.info("line 118");
// replyMessage("error", response, out);
replyMessage("your server url /plugins/fileupload/userservice?type=download&name="+filename, response, out);
catch (Exception e)
replyMessage("error", response, out);
Log.error("error while uploading file");
throw new ServletException("Cannot parse multipart request.", e);
/* InputStream inputStream=(InputStream) request.getAttribute("uploaded");
//InputStream inputStream=request.getInputStream();
File file = new File(name);
FileOutputStream fop = new FileOutputStream(file);
uploadFile(response, fop, inputStream);*/
//
private void replyMessage(String message,HttpServletResponse response, PrintWriter out)
response.setContentType("text/xml");
out.println("\"result\":\"" + message + "\"");
out.flush();
private void uploadFile(HttpServletResponse response, OutputStream out,InputStream inputStream)
final byte[] b = new byte[BUFFER_SIZE];
int count = 0;
amountWritten = 0;
do
// write to the output stream
try
out.write(b, 0, count);
catch (IOException e)
amountWritten += count;
// read more bytes from the input stream
try
count = inputStream.read(b);
catch (IOException e)
Log.info("error = "+e.getMessage());
while (count != -1 );
try
out.flush();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
Log.info("error = "+e.getMessage());
// the connection was likely terminated abrubtly if these are not equal
private void sendFile(HttpServletResponse response, OutputStream out,FileInputStream inputStream)
try
response.setContentType("video/mp4");
final byte[] b = new byte[BUFFER_SIZE];
int count = 0;
amountWritten = 0;
do
// write to the output stream
try
out.write(b, 0, count);
catch (IOException e)
//throw new XMPPException("error writing to output stream", e);
amountWritten += count;
// read more bytes from the input stream
try
count = inputStream.read(b);
catch (IOException e)
//throw new XMPPException("error reading from input stream", e);
while (count != -1 );
catch (Exception e)
// TODO: handle exception
Log.info("error = "+e.getMessage());
try
response.flushBuffer();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
// out.flush();
private void replyError(String error,HttpServletResponse response, PrintWriter out)
response.setContentType("text/xml");
out.println("<error>" + error + "</error>");
out.flush();
@Override
public void destroy()
super.destroy();
// Release the excluded URL
// AuthCheckFilter.removeExclude("userService/userservice");
【讨论】:
将文件上传到服务器并取回上传的网址后接下来要做什么 我正在开发一个聊天应用程序。现在我可以进行文字聊天了。我想在我的聊天应用程序中支持文件传输,所以我想到了使用 openfire 文件传输。但是你推荐了插件,你能解释一下使用插件进行文件传输的流程吗 好的,创建一个插件,将文件上传到服务器,当服务器回复您需要将该url发送给第二个用户的URL时,您可以在body中使用一些特殊字符前缀发送它它使接收者可以识别。第二个用户可以下载文件并将其保存在数据库中 这里是指导您如何在开火时创建插件的链接igniterealtime.org/builds/openfire/docs/latest/documentation/… 我正在使用 Vcard 来存储用户的图像、电话、电子邮件等信息。同样我们可以在 openfire 中将 Vcard 用于 MUC 组吗【参考方案2】:我是这样创建的
package org.jivesoftware.openfire.plugin;
import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
public class Fileupload implements Plugin
private static Logger Log = Logger.getLogger(Fileupload.class);
public static String directory="/usr/share/openfire/resources/videos";
public void initializePlugin(PluginManager manager, File pluginDirectory)
try
File file=new File(directory);
file.mkdir();
catch (Exception e)
// TODO: handle exception
Log.info("error while creating ../resources/Videos= "+ e.getMessage());
public void destroyPlugin()
【讨论】:
这是-1的正确答案,它对我有用【参考方案3】:我认为您还没有添加相同的提供者
登录后添加此方法
private static void Configure(Context context)
try
ProviderManager pm = ProviderManager.getInstance();
pm.addIQProvider("query", "urn:xmpp:groupvcard",
new GroupInfoVcard.Provider(context));
pm.addIQProvider("query", "jabber:iq:search",
new SearchItem.Provider(context));
System.out.println("SearchItem added");
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
pm = ProviderManager.getInstance();
pm.addExtensionProvider("active",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("composing",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("paused",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("inactive",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("gone",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
Log.e("DeliveryReceipt.ELEMENT", DeliveryReceipt.ELEMENT);
pm.addExtensionProvider(DeliveryReceipt.ELEMENT,
DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
pm.addIQProvider("list", "urn:xmpp:archive", new ListIQProvider(context));
pm.addIQProvider("chat", "urn:xmpp:archive", new ChatIQProvider());
System.out.println("ping provider added");
pm.addIQProvider("ping", "urn:xmpp:ping", new PingProvider());
System.out.println("ping provider added end");
pm.addExtensionProvider(DeliveryReceiptRequest.ELEMENT,
DeliveryReceipt.NAMESPACE,
new DeliveryReceiptRequest.Provider());
pm.addIQProvider("query", "jabber:iq:private",
new PrivateDataManager.PrivateDataIQProvider());
// Time
try
pm.addIQProvider("query", "jabber:iq:time",
Class.forName("org.jivesoftware.smackx.packet.Time"));
catch (ClassNotFoundException e)
System.err
.println("Can't load class for org.jivesoftware.smackx.packet.Time");
// Roster Exchange
pm.addExtensionProvider("x", "jabber:x:roster",
new RosterExchangeProvider());
// Message Events
pm.addExtensionProvider("x", "jabber:x:event",
new MessageEventProvider());
// Chat State
pm.addExtensionProvider("active",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("composing",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("paused",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("inactive",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
pm.addExtensionProvider("gone",
"http://jabber.org/protocol/chatstates",
new ChatStateExtension.Provider());
// Xhtml
pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im",
new XHTMLExtensionProvider());
// Group Chat Invitations
pm.addExtensionProvider("x", "jabber:x:conference",
new GroupChatInvitation.Provider());
// Service Discovery # Items
pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",
new DiscoverItemsProvider());
// Service Discovery # Info
pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",
new DiscoverInfoProvider());
// Data Forms
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
// MUC User
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user",
new MUCUserProvider());
// MUC Admin
pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin",
new MUCAdminProvider());
// MUC Owner
pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner",
new MUCOwnerProvider());
// Delayed Delivery
pm.addExtensionProvider("x", "jabber:x:delay",
new DelayInformationProvider());
pm.addExtensionProvider("delay", "urn:xmpp:delay",
new DelayInformationProvider());
// Version
try
pm.addIQProvider("query", "jabber:iq:version",
Class.forName("org.jivesoftware.smackx.packet.Version"));
catch (ClassNotFoundException e)
System.err
.println("Can't load class for org.jivesoftware.smackx.packet.Version");
// VCard
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
// Message Requests
pm.addIQProvider("offline", "http://jabber.org/protocol/offline",
new OfflineMessageRequest.Provider());
// Offline Message Indicator
System.out.println("offline provider added");
pm.addExtensionProvider("offline",
"http://jabber.org/protocol/offline",
new OfflineMessageInfo.Provider());
// Last Activity
pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
// SharedGroupsInfo
pm.addIQProvider("sharedgroup",
"http://www.jivesoftware.org/protocol/sharedgroup",
new SharedGroupsInfo.Provider());
// JEP-33: Extended Stanza Addressing
pm.addExtensionProvider("addresses",
"http://jabber.org/protocol/address",
new MultipleAddressesProvider());
// FileTransfer
pm.addIQProvider("si", "http://jabber.org/protocol/si",
new StreamInitiationProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
new BytestreamsProvider());
pm.addIQProvider("open", "http://jabber.org/protocol/ibb",
new OpenIQProvider());
pm.addIQProvider("data", "http://jabber.org/protocol/ibb",
new DataPacketProvider());
pm.addIQProvider("close", "http://jabber.org/protocol/ibb",
new CloseIQProvider());
pm.addExtensionProvider("data", "http://jabber.org/protocol/ibb",
new DataPacketProvider());
// Privacy
pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
// SHIM
pm.addExtensionProvider("headers", "http://jabber.org/protocol/shim",
new HeadersProvider());
pm.addExtensionProvider("header", "http://jabber.org/protocol/shim",
new HeaderProvider());
// PubSub
pm.addIQProvider("pubsub", "http://jabber.org/protocol/pubsub",
new PubSubProvider());
pm.addExtensionProvider("create", "http://jabber.org/protocol/pubsub",
new SimpleNodeProvider());
pm.addExtensionProvider("items", "http://jabber.org/protocol/pubsub",
new ItemsProvider());
pm.addExtensionProvider("item", "http://jabber.org/protocol/pubsub",
new ItemProvider());
pm.addExtensionProvider("subscriptions",
"http://jabber.org/protocol/pubsub",
new SubscriptionsProvider());
pm.addExtensionProvider("subscription",
"http://jabber.org/protocol/pubsub", new SubscriptionProvider());
pm.addExtensionProvider("affiliations",
"http://jabber.org/protocol/pubsub", new AffiliationsProvider());
pm.addExtensionProvider("affiliation",
"http://jabber.org/protocol/pubsub", new AffiliationProvider());
pm.addExtensionProvider("options", "http://jabber.org/protocol/pubsub",
new FormNodeProvider());
// PubSub owner
pm.addIQProvider("pubsub", "http://jabber.org/protocol/pubsub#owner",
new PubSubProvider());
pm.addExtensionProvider("configure",
"http://jabber.org/protocol/pubsub#owner",
new FormNodeProvider());
pm.addExtensionProvider("default",
"http://jabber.org/protocol/pubsub#owner",
new FormNodeProvider());
// PubSub event
pm.addExtensionProvider("event",
"http://jabber.org/protocol/pubsub#event", new EventProvider());
pm.addExtensionProvider("configuration",
"http://jabber.org/protocol/pubsub#event",
new ConfigEventProvider());
pm.addExtensionProvider("delete",
"http://jabber.org/protocol/pubsub#event",
new SimpleNodeProvider());
pm.addExtensionProvider("options",
"http://jabber.org/protocol/pubsub#event",
new FormNodeProvider());
pm.addExtensionProvider("items",
"http://jabber.org/protocol/pubsub#event", new ItemsProvider());
pm.addExtensionProvider("item",
"http://jabber.org/protocol/pubsub#event", new ItemProvider());
pm.addExtensionProvider("retract",
"http://jabber.org/protocol/pubsub#event",
new RetractEventProvider());
pm.addExtensionProvider("purge",
"http://jabber.org/protocol/pubsub#event",
new SimpleNodeProvider());
// Nick Exchange
pm.addExtensionProvider("nick", "http://jabber.org/protocol/nick",
new Nick.Provider());
// Attention
pm.addExtensionProvider("attention", "urn:xmpp:attention:0",
new AttentionExtension.Provider());
// XEP-184 Message Delivery Receipts
pm.addExtensionProvider("received", "urn:xmpp:receipts",
new DeliveryReceipt.Provider());
pm.addExtensionProvider("request", "urn:xmpp:receipts",
new DeliveryReceipt.Provider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
new BytestreamsProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",
new DiscoverItemsProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",
new DiscoverInfoProvider());
/*pm.addIQProvider("offline", "http://jabber.org/protocol/offline",
new OfflineMessageRequest.Provider());
// Offline Message Indicator
pm.addExtensionProvider("offline",
"http://jabber.org/protocol/offline",
new OfflineMessageInfo.Provider());*/
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
【讨论】:
在最近的 aSmack 版本中不再需要手动添加提供程序。 您好,我使用的是 asmack 最新版本,您必须添加用于存档、多用户聊天和文件传输的提供程序,检查此项并将其设为 -1 的 0 @Flow 你介意看看我的问题吗? link 谢谢!以上是关于Android asmack openfire接收文件的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 asmack android 从 Openfire 中检索一对一的聊天记录
Android 文件传输无法通过 XMPP 和 OpenFire 工作
aSmack 4.0.* XMPPTCPConnection 无法连接到 OpenFire 和 Ejabbered (SmackException$NoResponseException)