基于smack的即时聊天系统之文件传输功能实现
功能实现流程为:
1.文件发送方用户登录
2.确定文件的接收方和待发送文件路径
3.获取连接
4.根据连接获取文件接收方的完整jid(例如[email protected]/MiniQQ 2.3.6),其中MiniQQ 2.3.6为文件接收方用户客户端的resource,必须获取到,否则文件无法发送
5.发送文件
实现代码为:
<span style="font-size:18px;">public int TransFile(String toUser, String fileDir) { // final int flag[] = new int[] { 0 }; Connection conn = this.connection; ServiceDiscoveryManager serviceDiscoveryManager = new ServiceDiscoveryManager( conn); // System.out.println(conn.toString()); // System.out.println(this.sessionManager.getConnection().toString()); if (!toUser.contains("@")) { toUser = toUser + "@" + this.connection.getServiceName(); } // toUser = toUser +"/Spark 2.6.3"; Roster roster = connection.getRoster(); Presence pre = roster.getPresence(toUser); toUser = pre.getFrom(); if (!toUser.contains("/")) { //toUser = toUser + "/MiniQQ 2.3.6"; toUser = toUser + "/MiniQQ 2.3.6"; } System.out.println("向发送文件:" + toUser); // System.out.println(toUser); if (pre == null) { System.out.println("用户不存在"); return -1; } FileTransferManager transferManager = new FileTransferManager(conn); final File file = new File(fileDir); final OutgoingFileTransfer transfer = transferManager .createOutgoingFileTransfer(toUser); // FutureTask<Integer> task = new FutureTask<Integer>(); FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() { @Override public Integer call() throws Exception { int flag = 0; try { transfer.sendFile(file, "Sending"); while (!transfer.isDone()) { try { Thread.sleep(10L); } catch (InterruptedException e) { e.printStackTrace(); } if (transfer.getStatus() == FileTransfer.Status.in_progress) { System.out.println(transfer.getProgress()); // flag[0] = 0; } else { if (transfer.getStatus() == FileTransfer.Status.error) { System.out.println("file transport failed");// // flag[0] = -1; flag = -1; // return ; } if (transfer.getStatus() == FileTransfer.Status.refused) { System.out .println("file transport was refused"); // flag[0] = -1; flag = -1; // return ; } } } } catch (XMPPException e1) { e1.printStackTrace(); // return ; } return flag; } }); SwingUtilities.invokeLater(task); int flagRes = 0; while (true) { if (task.isDone()) { try { flagRes = task.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } break; } } return flagRes; }</span>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。