内置网页提供大文件下载内存溢出
项目需求,PC通过IP地址访问静态网页,网页提供文件下载,文件过大,直接oom,求老师指导
public class ClienDownloadService extends Service { private ExecutorService threadPool; private ServerSocket serverSocket; private InetSocketAddress address; private boolean isEnable; public IBinder onBind(Intent intent) { return null; } public void onCreate() { super.onCreate(); initPlatfrom(); startAsync(); } public void initPlatfrom() { threadPool = Executors.newCachedThreadPool(); } private void startAsync() { isEnable = true; new Thread(new Runnable() { public void run() { try { address = new InetSocketAddress(8098); serverSocket = new ServerSocket(); serverSocket.bind(address); while (isEnable) { final Socket socket = serverSocket.accept(); threadPool.execute(new Runnable() { public void run() { try { buileRemoteSocket(socket); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void buileRemoteSocket(Socket socket) throws Exception { InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { if (line.startsWith("GET")) { String uri = line.split(" ")[1]; response(socket, uri); } } } public void response(Socket socket, String assetsPath) throws Exception { assetsPath = assetsPath.substring(1); if (assetsPath.equals("")) { assetsPath = "index.html"; } InputStream in = getAssets().open(assetsPath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len = 0; while ((len = in.read(buffer)) != -1) { bos.write(buffer, 0, len); } byte[] raw = bos.toByteArray(); in.close(); OutputStream nos = socket.getOutputStream(); PrintStream printer = new PrintStream(nos); printer.println("HTTP/1.1 200 OK"); printer.println("Content-length:" + raw.length); if (assetsPath.endsWith(".html")) { printer.println("Content-Type:text/html"); } else if (assetsPath.endsWith(".js")) { printer.println("Content-Type:text/js"); } else if (assetsPath.endsWith(".css")) { printer.println("Content-Type:text/css"); } else if (assetsPath.endsWith(".jpg")) { printer.println("Content-Type:text/jpg"); } else if (assetsPath.endsWith(".png")) { printer.println("Content-Type:text/png"); } printer.println(); printer.write(raw); printer.flush(); printer.close(); } public void onDestroy() { super.onDestroy(); stopAsync(); } public void stopAsync() { isEnable = false; try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }