基于smack的即时聊天系统之文件接收功能实现

  1. 云栖社区>
  2. 博客>
  3. 正文

基于smack的即时聊天系统之文件接收功能实现

龙盛国际 2015-01-26 14:51:00 浏览709
展开阅读全文

实现思路为:

1.接收方用户登录

2.获取文件发送方用户名

3.获取需要接收的文件名

4.获取需要接收的文件大小

5.设置文件存放路径

6.接收文件

实现代码为:

public int SetTransFileCallBack(final Method method,
			final Object instance, final String downloadeDir) {
		FileTransferManager transferManager = new FileTransferManager(
				this.connection);

		transferManager.addFileTransferListener(new FileTransferListener() {
			public void fileTransferRequest(final FileTransferRequest request) {
				String fromwhere = request.getRequestor();
				int pos = fromwhere.lastIndexOf('@');
				String from = fromwhere.substring(0, pos);
				if (!from.equals("sharefilemanager"))
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							String fileName = request.getFileName();
							long fileSize = request.getFileSize();
							String requestor = request.getRequestor();
							String bareJID = org.jivesoftware.smack.util.StringUtils
									.parseBareAddress(requestor);

							ByteFormat format = new ByteFormat();
							String text = format.format(fileSize);

							IncomingFileTransfer transfer = request.accept();
							File filecreate = new File(downloadeDir);
							if (!filecreate.exists()) {
								filecreate.mkdirs();
							}
							File downloadedFile = new File(downloadeDir,
									request.getFileName());
							try {
								transfer.recieveFile(downloadedFile);
								while (true) {
									if (transfer.getStatus() == FileTransfer.Status.complete) {
										try {
											method.invoke(instance,
													new Object[] { fileName,
															bareJID, text,
															downloadeDir });
										} catch (IllegalArgumentException e) {
											e.printStackTrace();
										} catch (IllegalAccessException e) {
											e.printStackTrace();
										} catch (InvocationTargetException e) {
											e.printStackTrace();
										}
										return;
									}
									try {
										Thread.sleep(10L);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
								}
							} catch (XMPPException e) {
								e.printStackTrace();
							}
						}
					});
			}
		});
		return 0;
	}


网友评论

登录后评论
0/500
评论
龙盛国际
+ 关注