问一个socket传输文件的问题

jianpc 2009-03-09 03:55:26
要利用socket向客户端传容量比较大的文件,比如大的图片,大的视频文件等,有什么好的优化方案吗?
把文件切割成小片的话,怎么切割,有具体的实例吗?

谢谢大家帮助。
...全文
132 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
jianpc 2009-03-10
  • 打赏
  • 举报
回复
谢谢大家。
angel_bear 2009-03-09
  • 打赏
  • 举报
回复
4楼的推荐文章应该提够一点思路,改改应该能够运用到socket上来。
1.分割文件
2.分多个线程,每个线程传输一个分割快到客户端
3.客户端等所有接受线程都完成的时候在合并文件
shuanlarousi1 2009-03-09
  • 打赏
  • 举报
回复
http://www.99inf.net/SoftwareDev/Java/54606.htm
利用多线程技术也能够提高效率
数据已经读入内存中,因为要对这些数据进行一下处理,然后再传图片、视频
这个文件分割技术的代码也许会对你有些帮助
public class FileDivision { // 单个文件大小
private static final long SPLIT_SIZE = 5 * 1024 * 1024;
/** *分割文件 * * @author Jason,Wang * @param filePath * 要分割的文件路径 * @return int 分割的数量 */
public static int split(String filePath)
{ // 子文件数量 int number = 1;
// 文件通道 FileChannel in = null;
try { in = new FileInputStream(filePath).getChannel();
// 文件长度 long fileLength = in.size();
long position = 0; while (position < fileLength)
{ // 子文件 FileChannel out = new FileOutputStream(filePath + (number++)) .getChannel();
in.transferTo(position, SPLIT_SIZE, out); out.close(); position += SPLIT_SIZE; } }
catch (Exception e) { e.printStackTrace(); number = 1; }
finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return number; } }


zhangpeixv 2009-03-09
  • 打赏
  • 举报
回复
nio
非阻塞I/O流
swoky 2009-03-09
  • 打赏
  • 举报
回复
我也来个分割文件的程序,供参考,合并的未贴:

public class FileDivision {
// 单个文件大小
private static final long SPLIT_SIZE = 5 * 1024 * 1024;

/**
*分割文件
*
* @author Jason,Wang
* @param filePath
* 要分割的文件路径
* @return int 分割的数量
*/
public static int split(String filePath) {
// 子文件数量
int number = 1;
// 文件通道
FileChannel in = null;
try {
in = new FileInputStream(filePath).getChannel();
// 文件长度
long fileLength = in.size();
long position = 0;
while (position < fileLength) {
// 子文件
FileChannel out = new FileOutputStream(filePath + (number++))
.getChannel();
in.transferTo(position, SPLIT_SIZE, out);
out.close();
position += SPLIT_SIZE;
}
} catch (Exception e) {
e.printStackTrace();
number = 1;
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return number;
}
}
jianpc 2009-03-09
  • 打赏
  • 举报
回复
已经是在线程里面传输文件了。再起线程的话,怕不好管理。。
kokobox 2009-03-09
  • 打赏
  • 举报
回复
文件切割的程序:http://www.99inf.net/SoftwareDev/Java/54606.htm

利用多线程并发读写。效率可能会快一点。

wafj1984 2009-03-09
  • 打赏
  • 举报
回复
mark
zhangpeixv 2009-03-09
  • 打赏
  • 举报
回复
mark
jianpc 2009-03-09
  • 打赏
  • 举报
回复
数据已经读入内存中,因为要对这些数据进行一下处理,然后再传。图片、视频只是举例:)

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧