首页 > 代码库 > 基于smack的即时聊天系统之文件接收功能实现

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

实现思路为:

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;
	}


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