浏览 2834 次
锁定老帖子 主题:TCP实现局域网文件传输细节
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-03-07
最后修改:2009-03-07
续上次讲过UDP传输文件,这次简要讲下关于TCP文件传输的发送端与接收端.tcp传输主要关键地方就是文件末尾的处理 发送端代码:
private void sendFile(File f) throws Exception { oos.writeUnshared(f); oos.writeLong(f.length()); FileInputStream fins = new FileInputStream(f); byte[] buf = new byte[8192]; int size = 0; while ((size = fins.read(buf)) != -1) { oos.write(buf, 0, size); } System.out.println("发送方发送文件:" + f + " 完毕"); oos.flush(); fins.close(); }
接收端代码:
/** * 处理对方发过来的文件 */ private void doReceiveFile(String savePath) throws Exception { File f = (File) ois.readUnshared();//文件 long len = ois.readLong(); System.out.println("接收方 收到发送方的文件:" + f + " 文件大小:" + len); File file = new File(savePath, f.getName()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } BufferedOutputStream fous = new BufferedOutputStream(new FileOutputStream(file)); byte[] buffer = new byte[8192]; int lengths = -1;//实现每次接收到的数组长度 int accepts = 0;//当前已经传的文件长度 int canRead = (int) (len - accepts - 8192 < 0 ? len - accepts : 8192);//处理文件末尾 while ((lengths = ois.read(buffer, 0, canRead)) > 0) { fous.write(buffer, 0, lengths); accepts += lengths; canRead = (int) (len - accepts - 8192 < 0 ? len - accepts : 8192); } fous.close(); System.out.println("接收方接收文件完毕"); }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |