我想寫一個位於Linux服務器上的java servlet,它可以被客戶端用來下載視頻文件。它適用於文件大小很小(可能小於2 MB)的情況,但較大的文件大小會返回錯誤:org.apache.catalina.connector.ClientAbortException: java.io.IOException: Broken pipe
。爲什麼Java servlet在文件大小大於2 MB時給ClientAbortException?
搜索Google後,當客戶端斷開連接時出現此錯誤。在我的情況下,我使用客戶端,並且可以確認我沒有做任何會破壞連接的事情(至少不是故意的) - 當發生此錯誤時,瀏覽器保持打開狀態等。
任何想法可能會導致此(以及如何解決)?
public class GetFile extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String filename ="init_java";
try {
// get user parameters
filename = req.getParameter("fileId"); // complete path to video file
//res.setContentType("video/mp4"); //not working
res.setContentType("application/x-download");
File file=new File(filename);
if (file.exists()) {
res.setHeader("Content-Disposition", "inline; filename=\""+filename+"\"");
res.setHeader("Cache-Control", "cache, must-revalidate");
//res.setHeader("Pragma", "public"); // not sure when to use
returnFile(filename, res.getOutputStream());
} else {
//error handling goes here
}
} catch (Exception e) {
...
} finally {
...
}
}
private static void returnFile(String filename, OutputStream out) throws FileNotFoundException, IOException {
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(filename));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
} finally {
if (in != null) in.close();
}
}
}
UPDATE 1
我看到在mod_jk.log
文件以下錯誤(其從Apache Web服務器以GlassFish應用服務器的請求傳送):
[info] init_jk::mod_jk.c (3383): mod_jk/1.2.40 initialized
[error] ajp_connection_tcp_get_message::jk_ajp_common.c (1313): wrong message format 0xcad5 from ::1:8009
[error] ajp_get_reply::jk_ajp_common.c (2204): (worker1) Tomcat is down or network problems. Part of the response has already been sent to the client
[info] ajp_service::jk_ajp_common.c (2673): (worker1) sending request to tomcat failed (recoverable), because of protocol error (attempt=1)
[info] ajp_process_callback::jk_ajp_common.c (2000): Writing to client aborted or client network problems
[info] ajp_service::jk_ajp_common.c (2673): (worker1) sending request to tomcat failed (unrecoverable), because of client write error (attempt=2)
[info] jk_handler::mod_jk.c (2799): Aborting connection for worker=worker1
它似乎跟蹤了我所觀察到的,但我不是這裏的專家 - 這是否提供了對可能是什麼根源的任何洞察?
嘗試'.flush()'一切後,輸出流已被寫入其中。 – 2014-10-17 18:20:12
謝謝@FabianBarney,我在'returnFile()'中的while循環後面添加了'out.flush();'但它沒有什麼區別。 – user46688 2014-10-17 18:54:01
這可能是一個基礎設施問題 - 例如防火牆/路由器會丟棄某種類型和持續時間的連接。 – 2014-10-17 19:17:35