我正在尝试使用套接字实现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)
堆栈跟踪显示问题来自于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();
}
}
}
while(true)
循环必须正常退出。编辑中的新代码存在一个新问题,即如果套接字异常关闭,则while
循环将永远旋转。 - bond