java.net.SocketException:通过对等方重置连接:套接字写入错误提供文件时

我正在尝试使用套接字实现HTTP服务器。 如果客户端(例如浏览器)请求目录,则服务器显示可用文件列表。 当客户端请求文件时出现问题。 我收到以下错误:

java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113) at java.net.SocketOutputStream.write(SocketOutputStream.java:159) at cf.charly1811.java.web.RequestHandler.writeFile(RequestHandler.java:152) at cf.charly1811.java.web.RequestHandler.processRequest(RequestHandler.java:139) at cf.charly1811.java.web.RequestHandler.handleRequest(RequestHandler.java:110) at cf.charly1811.java.web.RequestHandler.run(RequestHandler.java:86) at java.lang.Thread.run(Thread.java:745) 

stacktrace显示问题来自writeFile()方法:

 private void writeFile(File request) throws IOException { InputStream byteReader = new BufferedInputStream(new FileInputStream(request)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = byteReader.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byteReader.close(); } 

但我无法弄清楚出了什么问题。 你能帮助我吗?

编辑

谢谢大家的回答。 在我读完你的答案之后,我明白问题在于Socket发生错误时。 这是我的错误代码:

 // Method to process a single request handleRequest() throw IOException { // process here // if the client request a file writeFile(); // close socket when the request is processed } // The method is called public run() { try{ // If an error occurs the try/catch won't be called because it is implemented outside the loop. So when an IOException occurs, the loop just stop and exit the program while(true) { handleRequest(); } } catch(IOException e) { // Handle exception here } } 

我的新代码看起来像这样:

 // Method to process a single request handleRequest() { try { // process here // if the client request a file writeFile(); // close socket when the request is processed } // If this exception occurs the catch() method will be called catch(IOException e) { // handle exception here } } // The method is called public run() { while(true) { handleRequest(); } } } 

TCP套接字可能“关闭”并且您的代码尚未得到通知。

这是一个生命周期的动画。 http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle

基本上,连接由客户端关闭。 您已经throws IOException并且SocketException扩展了IOException 。 这工作得很好。 您只需要正确处理IOException因为它是api的正常部分。

编辑:当在不存在或已关闭的套接字上接收到数据包时,会发生RST数据包。 您的申请没有区别。 根据实施方式, reset状态可能会粘连和closed将永远不会正式发生。

此问题通常是由写入已由对等方关闭的连接引起的。 在这种情况下,它可以指示用户例如取消了下载。