安卓基于Socket的大文件串行上传队列、后台持续上传及服务端接收实现咨询
可落地方案架构设计
这套方案完全适配你当前单Socket通信、大文件传输、串行队列调度、后台连续运行的需求,全程用安卓原生能力实现,不需要引入第三方框架:
- 针对单Socket无法并发传输的限制:采用单线程阻塞队列做任务调度,所有上传任务在独立后台线程串行执行,从根源上避免多个文件抢占同一个Socket连接导致的TCP流串包问题
- 针对上传连续性要求:放弃普通后台Service,改用前台Service + 任务本地持久化的组合,哪怕应用切后台、用户从最近任务划掉应用,只要进程没被系统强杀,已触发的上传任务就会持续运行直到完成;就算进程意外被杀,下次打开应用也能自动加载未传完的任务做断点续传
- 针对12MB-200MB的大文件传输场景:全程采用分块流式读写,任何环节都不把完整文件加载进内存,从机制上避免大文件导致的OOM问题
安卓端核心实现逻辑
任务队列调度层
核心用LinkedBlockingQueue做阻塞队列,搭配独立的HandlerThread做单线程消费,没有任务的时候线程自动挂起,不消耗CPU:
// 上传任务实体类,记录文件基本信息和断点位置 public class UploadTask { public String localFilePath; public String targetFileName; public long totalFileSize; public long transferredBytes; }
public class UploadQueueManager { private static volatile UploadQueueManager instance; // 阻塞任务队列,保证串行执行 private final BlockingQueue<UploadTask> taskQueue = new LinkedBlockingQueue<>(); private HandlerThread uploadWorkerThread; private Handler uploadHandler; private Socket activeSocket; private DataOutputStream socketOutput; public static UploadQueueManager getInstance() { if (instance == null) { synchronized (UploadQueueManager.class) { if (instance == null) instance = new UploadQueueManager(); } } return instance; } // 初始化队列消费逻辑 public void init(Context context) { uploadWorkerThread = new HandlerThread("UploadWorker", Process.THREAD_PRIORITY_BACKGROUND); uploadWorkerThread.start(); uploadHandler = new Handler(uploadWorkerThread.getLooper()); startQueueLoop(); } // 对外暴露的添加任务方法 public void addUploadTask(UploadTask task) { // 先把任务持久化到本地SQLite,防止进程被杀丢失任务记录 persistTaskToLocal(task); taskQueue.offer(task); } // 队列循环消费核心逻辑 private void startQueueLoop() { uploadHandler.post(() -> { while (!Thread.currentThread().isInterrupted()) { try { // 阻塞等待下一个任务,没有任务时线程挂起 UploadTask currentTask = taskQueue.take(); // 校验Socket连接有效性,断开就重连 ensureSocketAlive(); // 开始传输当前文件 transferSingleFile(currentTask); // 传输完成后删除本地持久化的任务记录 removePersistedTask(currentTask); } catch (Exception e) { // 传输出错时退避1秒重试,避免疯狂重连打满网络 uploadHandler.postDelayed(() -> { // 错误处理:更新任务状态为失败,回到队列等待重试 }, 1000); } } }); } }
后台保活层
安卓8.0之后普通后台Service会被系统强制回收,完全没法支撑长时上传,必须用前台Service:
public class UploadKeepAliveService extends Service { @Override public void onCreate() { super.onCreate(); // 把Service优先级提升到前台级,避免被系统回收 startForeground(1001, buildUploadNotification()); // 初始化上传队列 UploadQueueManager.getInstance().init(this); // 加载本地持久化的未完成任务,自动续传 UploadQueueManager.getInstance().loadPersistedTasks(); } // 构建常驻上传通知 private Notification buildUploadNotification() { NotificationChannel channel = new NotificationChannel( "upload_channel", "文件上传", NotificationManager.IMPORTANCE_LOW); NotificationManager notifyManager = getSystemService(NotificationManager.class); notifyManager.createNotificationChannel(channel); return new Notification.Builder(this, "upload_channel") .setContentTitle("文件上传进行中") .setSmallIcon(R.drawable.ic_upload) .build(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
注意:启动这个Service的时候必须用
startForegroundService()方法,只要是用户主动勾选文件触发的上传,就完全符合安卓12以上的后台启动Service权限要求,不会抛异常。
文件传输层
传输时采用8MB大小的分块缓冲区读写,不把整个文件读进内存,支持断点续传:
private void transferSingleFile(UploadTask task) throws IOException { // 先发送文件元信息,让服务器提前准备好接收空间 socketOutput.writeUTF(task.targetFileName); socketOutput.writeLong(task.totalFileSize); socketOutput.flush(); // 从上次中断的位置开始读文件 FileInputStream fis = new FileInputStream(task.localFilePath); fis.skip(task.transferredBytes); byte[] buffer = new byte[8 * 1024]; int readLen; // 分块读写,避免大文件占满内存 while ((readLen = fis.read(buffer)) != -1) { socketOutput.write(buffer, 0, readLen); task.transferredBytes += readLen; // 回调更新进度,切后台时同步到通知栏 updateUploadProgress(task); } socketOutput.flush(); fis.close(); }
服务器端接收逻辑
因为客户端是单Socket长连接串行传文件,服务器端不需要做复杂的并发调度,只需要在同一个连接里循环读元信息、接文件即可,避免流处理混乱:
public class FileReceiveServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("文件接收服务已启动,监听端口8888"); while (true) { // 接受客户端的长连接 Socket clientConn = serverSocket.accept(); System.out.println("客户端连接建立: " + clientConn.getInetAddress()); // 给每个客户端连接开一个独立线程处理 new Thread(() -> { try (DataInputStream input = new DataInputStream(clientConn.getInputStream())) { // 同一个连接里循环接收多个文件 while (!clientConn.isClosed()) { // 先读客户端发的文件元信息 String fileName = input.readUTF(); long fileSize = input.readLong(); System.out.println("开始接收文件: " + fileName + ",总大小: " + fileSize/1024/1024 + "MB"); // 把文件写到服务器本地存储 FileOutputStream fos = new FileOutputStream("/data/server/upload/" + fileName); byte[] buffer = new byte[8 * 1024]; long receivedBytes = 0; int readLen; // 直到收够文件总大小为止 while (receivedBytes < fileSize) { readLen = input.read(buffer, 0, (int)Math.min(buffer.length, fileSize - receivedBytes)); if (readLen == -1) break; fos.write(buffer, 0, readLen); receivedBytes += readLen; } fos.flush(); fos.close(); System.out.println("文件 " + fileName + " 接收完成,共 " + receivedBytes/1024/1024 + "MB"); } } catch (IOException e) { e.printStackTrace(); System.out.println("客户端连接断开"); } }).start(); } } }
落地踩坑提醒
- 给Socket开启TCP心跳保活,每30秒发一个空包,避免运营商或服务器把空闲长连接掐断,导致大文件传到一半断连
- 给Socket设置
tcpNoDelay = true,关掉Nagle算法,减少小包传输的网络延迟,提升大文件传输速度- 任务持久化不要存在SharedPreferences里,简单的任务列表存在SQLite即可,避免SP在高并发下丢数据
- 所有Socket读写操作全在后台单线程跑,绝对不要放主线程
内容的提问来源于stack exchange,提问作者khaled sabri
相关产品推荐
相关产品推荐

