Android应用开发之使用Socket进行大文件断点上传续传
在Android中上传文件可以采用HTTP方式,也可以采用Socket方式,但是HTTP方式不能上传大文件,这里介绍一种通过Socket方式来进行断点续传的方式,服务端会记录下文件的上传进度,当某一次上传过程意外终止后,下一次可以继续上传,这里用到的其实还是J2SE里的知识。
这个上传程序的原理是:客户端第一次上传时向服务端发送“Content-Length=35;filename=WinRAR_3.90_SC.exe;sourceid=“这种格式的字符串,服务端收到后会查找该文件是否有上传记录,如果有就返回已经上传的位置,否则返回新生成的sourceid以及position为0,类似”sourceid=2324838389;position=0“这样的字符串,客户端收到返回后的字符串后再从指定的位置开始上传文件。
首先是服务端代码:
SocketServer.java
- package com.android.socket.server;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.io.PushbackInputStream;
- import java.io.RandomAccessFile;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Properties;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import com.android.socket.utils.StreamTool;
- public class SocketServer {
- private ExecutorService executorService;// 线程池
- private ServerSocket ss = null;
- private int port;// 监听端口
- private boolean quit;// 是否退出
- private Map<Long, FileLog> datas = new HashMap<Long, FileLog>();// 存放断点数据,最好改为数据库存放
- public SocketServer(int port) {
- this.port = port;
- // 初始化线程池
- executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
- .availableProcessors() * );
- }
- // 启动服务
- public void start() throws Exception {
- ss = new ServerSocket(port);
- while (!quit) {
- Socket socket = ss.accept();// www.linuxidc.com接受客户端的请求
- // 为支持多用户并发访问,采用线程池管理每一个用户的连接请求
- executorService.execute(new SocketTask(socket));// 启动一个线程来处理请求
- }
- }
- // 退出
- public void quit() {
- this.quit = true;
- try {
- ss.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws Exception {
- SocketServer server = );
- server.start();
- }
- private class SocketTask implements Runnable {
- private Socket socket;
- public SocketTask(Socket socket) {
- this.socket = socket;
- }
- @Override
- public void run() {
- try {
- System.out.println("accepted connenction from "
- + socket.getInetAddress() + " @ " + socket.getPort());
- PushbackInputStream inStream = new PushbackInputStream(
- socket.getInputStream());
- // 得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=
- // 如果用户初次上传文件,sourceid的值为空。
- String head = StreamTool.readLine(inStream);
- System.out.println(head);
- if (head != null) {
- // 下面从协议数据中读取各种参数值
- String[] items = head.split(";");
- String filelength = items[].substring(items[].indexOf();
- String filename = items[].substring(items[].indexOf();
- String sourceid = items[].substring(items[].indexOf();
- Long id = System.currentTimeMillis();
- FileLog log = null;
- if (null != sourceid && !"".equals(sourceid)) {
- id = Long.valueOf(sourceid);
- log = find(id);//查找上传的文件是否存在上传记录
- }
- File file = null;
- ;
- if(log==null){//如果上传的文件不存在上传记录,为文件添加跟踪记录
- String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date());
- File dir = new File("file/"+ path);
- if(!dir.exists()) dir.mkdirs();
- file = new File(dir, filename);
- if(file.exists()){//如果上传的文件发生重名,然后进行改名
- filename = filename.substring(, filename.indexOf()+ dir.listFiles().length+ filename.substring(filename.indexOf("."));
- file = new File(dir, filename);
- }
- save(id, file);
- }else{// 如果上传的文件存在上传记录,读取上次的断点位置
- file = new File(log.getPath());//从上传记录中得到文件的路径
- if(file.exists()){
- File logFile = new File(file.getParentFile(), file.getName()+".log");
- if(logFile.exists()){
- Properties properties = new Properties();
- properties.load(new FileInputStream(logFile));
- position = Integer.valueOf(properties.getProperty("length"));//读取断点位置
- }
- }
- }
- OutputStream outStream = socket.getOutputStream();
- String response = "sourceid="+ id+ ";position="+ position+ "\r\n";
- //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0
- //sourceid由服务生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传
- outStream.write(response.getBytes());
- RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
- ) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度
- fileOutStream.seek(position);//移动文件指定的位置开始写入数据
- ];
- ;
- int length = position;
- ){//从输入流中读取数据写入到文件中
- fileOutStream.write(buffer, , len);
- length += len;
- Properties properties = new Properties();
- properties.put("length", String.valueOf(length));
- FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));
- properties.store(logFile, null);//实时记录文件的最后保存位置
- logFile.close();
- }
- if(length==fileOutStream.length()) delete(id);
- fileOutStream.close();
- inStream.close();
- outStream.close();
- file = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if(socket != null && !socket.isClosed()) socket.close();
- } catch (IOException e) {}
- }
- }
- }
- public FileLog find(Long sourceid) {
- return datas.get(sourceid);
- }
- // 保存上传记录
- public void save(Long id, File saveFile) {
- // 日后可以改成通过数据库存放
- datas.put(id, new FileLog(id, saveFile.getAbsolutePath()));
- }
- // 当文件上传完毕,删除记录
- public void delete(long sourceid) {
- if (datas.containsKey(sourceid))
- datas.remove(sourceid);
- }
- private class FileLog {
- private Long id;
- private String path;
- public FileLog(Long id, String path) {
- super();
- this.id = id;
- this.path = path;
- }
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- }
- }
ServerWindow.java
- package com.android.socket.server;
- import java.awt.BorderLayout;
- import java.awt.Frame;
- import java.awt.Label;
- import java.awt.event.WindowEvent;
- import java.awt.event.WindowListener;
- public class ServerWindow extends Frame{
- private SocketServer server;
- private Label label;
- public ServerWindow(String title){
- super(title);
- server = );
- label = new Label();
- add(label, BorderLayout.PAGE_START);
- label.setText("服务器已经启动www.linuxidc.com");
- this.addWindowListener(new WindowListener() {
- @Override
- public void windowOpened(WindowEvent e) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- server.start();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
- @Override
- public void windowIconified(WindowEvent e) {
- }
- @Override
- public void windowDeiconified(WindowEvent e) {
- }
- @Override
- public void windowDeactivated(WindowEvent e) {
- }
- @Override
- public void windowClosing(WindowEvent e) {
- server.quit();
- System.exit();
- }
- @Override
- public void windowClosed(WindowEvent e) {
- }
- @Override
- public void windowActivated(WindowEvent e) {
- }
- });
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- ServerWindow window = new ServerWindow("文件上传服务端");
- window.setSize(, );
- window.setVisible(true);
- }
- }
工具类StreamTool.java
- package com.android.socket.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PushbackInputStream;
- public class StreamTool {
- public static void save(File file, byte[] data) throws Exception {
- FileOutputStream outStream = new FileOutputStream(file);
- outStream.write(data);
- outStream.close();
- }
- public static String readLine(PushbackInputStream in) throws IOException {
- ];
- int room = buf.length;
- ;
- int c;
- loop: while (true) {
- switch (c = in.read()) {
- :
- case '\n':
- break loop;
- case '\r':
- int c2 = in.read();
- )) in.unread(c2);
- break loop;
- default:
- ) {
- char[] lineBuffer = buf;
- buf = ];
- room = buf.length - offset - ;
- System.arraycopy(lineBuffer, , buf, , offset);
- }
- buf[offset++] = (char) c;
- break;
- }
- }
- ) && (offset == )) return null;
- , offset);
- }
- /**
- * 读取流
- * @param inStream
- * @return 字节数组
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- ];
- ;
- ){
- outSteam.write(buffer, , len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
Android客户端代码:

Android应用开发之使用Socket进行大文件断点上传续传的更多相关文章
- Android中Socket大文件断点上传
原文:http://blog.csdn.net/shimiso/article/details/8529633 什么是Socket? 所谓Socket通常也称作“套接字”,用于描述IP地址和端口,是一 ...
- asp.net 如何实现大文件断点上传功能?
之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...
- 大文件断点上传 js+php
/* * js */ function PostFile(file, i, t) { console.log(1); var name = file.name, //文件名 size = fi ...
- ASP.NET大文件断点上传
HTML部分 <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="index.aspx. ...
- 利用Socket进行大文件传输
分类: WINDOWS 最近接触到利用socket进行大文件传输的技术,有些心得,与大家分享.首先看看这个过程是怎么进行的(如下图): 所以,我们需要三个socket在窗体加载的时候初始化: ...
- 基于socket实现大文件上传
import socket 1.客户端: 操作流程: 先拿到文件--->获取文件大小---->创建字典 1.制作表头 header 如何得到 他是一个二进制字符串 序列化得到 字典字符串 ...
- ios开发网络学习四:NSURLConnection大文件断点下载
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- 使用webuploader组件实现大文件分片上传,断点续传
本人在2010年时使用swfupload为核心进行文件的批量上传的解决方案.见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案. 本人在2013年时使用plupload为核心 ...
- Java 断点下载(下载续传)服务端及客户端(Android)代码
原文: Java 断点下载(下载续传)服务端及客户端(Android)代码 - Stars-One的杂货小窝 最近在研究断点下载(下载续传)的功能,此功能需要服务端和客户端进行对接编写,本篇也是记录一 ...
随机推荐
- Centos7 grep命令简介
grep 是一个最初用于 Unix 操作系统的命令行工具.在给出文件列表或标准输入后,grep会对匹配一个或多个正则表达式的文本进行搜索,并只输出匹配(或者不匹配)的行或文本. grep 可根据提供的 ...
- Java-多线程与单例
最近在公司写需求时遇到了多线程与单例一同出现的情况. 这个时候想到的就是线程安全以及单例的定义了,虽然单例指的是在内存中它只有一份,但是并不是说就是线程安全的. 所以,我当时就到网上找了关于多线程下单 ...
- Apache Spark 2.2.0 中文文档
Apache Spark 2.2.0 中文文档 - 快速入门 | ApacheCN Geekhoo 关注 2017.09.20 13:55* 字数 2062 阅读 13评论 0喜欢 1 快速入门 使用 ...
- 《Cracking the Coding Interview》——第13章:C和C++——题目5
2014-04-25 19:59 题目:C的关键字volatile有什么用? 解法:搞硬件设计的人好像更关注这个关键字.volatile本身是易变的意思,应该和persistent有反义词关系吧.说一 ...
- 《Cracking the Coding Interview》——第2章:链表——题目7
2014-03-18 02:57 题目:检查链表是否是回文的,即是否中心对称. 解法:我的做法是将链表从中间对半拆成两条,然后把后半条反转,再与前半条对比.对比完了再将后半条反转了拼回去.这样不涉及额 ...
- C/C++学习笔记--指针(Pointer)
定义指针 一般类型: type_name * var_name; 例如: int _var = 1555; int * _var_addr=&_var; 一般类型数组类:type_name ...
- Git——1.简介
关于版本控制 Git基础 安装Git 初始运行Git前的配置 获取帮助 关于版本控制 版本控制(VCS)是一种记录一个或若干文件内容变化,以便将来查阅特定版本修订情况的系统. 本地版本控制系统 大多都 ...
- 深入理解net core中的依赖注入、Singleton、Scoped、Transient(四)【转】
原文链接:https://www.cnblogs.com/gdsblog/p/8465401.html 相关文章: 深入理解net core中的依赖注入.Singleton.Scoped.Transi ...
- Horn–Schunck 光流法与其算法理解(gup cuda)
1. 基于Horn-Schunck模型的光流算法 1.1 光流的约束条件 光流 的假设条件认为图像序列,在时间t 的某一像素点与在时间t+1的这一像素点的偏移量保持不变,即 .这就是灰度值守恒 ...
- PHP命名空间与use
当在一个大型项目很多程序员书写模板时,最怕出现的问题就是命名,如果一个PHP脚本出现了同名的类或者方法,就会报错(fatal error),使用命名空间可以 解决这个问题 知识点: 命名空间names ...