【问题标题】:How to fix "Exception in thread "main" java.net.SocketException: Connection reset"如何修复“线程“主”java.net.SocketException:连接重置中的异常”
【发布时间】:2019-06-13 19:53:36
【问题描述】:

我正在尝试设置一个可以发送和接收文件的 java 程序。

我知道这个网站上有类似的问题,但我在阅读这些内容后遇到了麻烦。

我关注了这个视频:https://www.youtube.com/watch?v=WeaB8pAGlDw&ab_channel=Thecodersbay

它在他的视频中有效,我不确定我做错了什么。第一个 java 文件运行得很好,但是当我尝试运行第二个时,我得到了这个错误:

Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at fileSender.fileclient.main(fileclient.java:19)

我尝试使用其他一些端口,但这并没有解决问题。

这是我现在拥有的:

文件服务器文件:

package fileSender;

import java.io.*; 
import java.net.*; 

public class fileserver 
{
private static ServerSocket s;
private static FileInputStream fr;

public static void main(String[] args) throws Exception
{
    s = new ServerSocket(1418);
    Socket sr = s.accept();   //accept the connection

    fr = new FileInputStream("C:\\Users\\Anon\\Desktop\\folder\\testfile.txt");
    byte b[] = new byte[2002];   //before reading, a byte has to be declared. byte data includes the size of the file. if the size is unknown, use a random one I guess 
    fr.read(b, 0, b.length);   //the byte b, start reading the file at 0, and stop reading at the end of it. read from start to finish, and store it as b 

    OutputStream os = sr.getOutputStream();   
    os.write(b, 0, b.length);   //b variable will be sent with this. again, starts at 0, and ends at the length of the byte b 


}

}

这是客户端文件:

package fileSender;

import java.io.*;   //the whole thing
import java.net.*; 

public class fileclient 
{
private static Socket sr;
private static FileOutputStream fr;

public static void main(String[] args) throws Exception
{
    byte []b = new byte[2002];   //size from earlier. what the person gets 

    sr = new Socket("localhost",1418);
    InputStream is = sr.getInputStream();   //capturing the stream

    fr = new FileOutputStream("C:\\Users\\Anon\\Desktop\\testfile.txt");
    is.read(b, 0, b.length);   //will capture the stream of "is". again, whole file, 0 to end 

    fr.write(b, 0, b.length);   //writes the whole content into a file 

}
}

我尝试了很多评论,以便我能够理解事情。

提前致谢:)

【问题讨论】:

  • 确定文件的长度为 2002 字节(或更多)吗? --- 无论如何,代码的一个主要问题是你没有close() 任何东西。解决这个问题,也许事情会更好,例如因为关闭会导致缓冲区被刷新。

标签: java sockets inputstream outputstream


【解决方案1】:

所以,Connection Reset 表示套接字从另一端关闭。考虑到您的“服务器”正在做什么,这是非常合乎逻辑的。

当客户端连接时,您的服务器正在接受连接,从文件中读取最多 2002 个字节,将其发送到客户端并终止应用程序。此时,套接字sr 将与应用程序的其余资源一起关闭。此时,仍在读取InputStream 的客户端将收到套接字不再有效的通知,并引发该异常。

你应该检查testfile.txt是否写入成功。 可能没问题,尽管我不会让服务器如此突然地断开连接。我会让客户端正常关闭,或者在不活动后使客户端连接超时,因为在从 TCP 缓冲区读取所有数据之前,您可能会遇到 Connection Reset 错误。 (TCP 错误往往会更快地传达。)

【讨论】:

  • 谢谢!原来我的问题是我没有正确的文件路径,但我以后会使用你的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多