gpt4 book ai didi

java.net.SocketException : Connection reset by peer: socket write error When serving a file 异常

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:53 26 4
gpt4 key购买 nike

我正在尝试使用套接字实现 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();
}
}
}

最佳答案

TCP 套接字可能正在“关闭”而您的代码尚未收到通知。

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

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

编辑:RST 数据包在不存在或已关闭的套接字上接收到数据包时发生。您的应用程序没有区别。根据实现情况,reset 状态可能会持续,而 closed 永远不会正式发生。

关于java.net.SocketException : Connection reset by peer: socket write error When serving a file 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25611741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com