如何修复“线程“主”java.net.SocketException:连接重置中的异常”

我正在尝试设置一个可以发送和接收文件的 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 


}

}

我试图发表很多评论,以便我能够理解事情。


提前致谢 :)


白衣非少年
浏览 223回答 1
1回答

拉莫斯之舞

因此,Connection Reset意味着套接字从另一端关闭。考虑到您的“服务器”在做什么,这是非常合乎逻辑的。当客户端连接时,您的服务器正在接受连接,从文件中读取最多 2002 个字节,将其发送到客户端并终止应用程序。此时,套接字sr将与应用程序的其余资源一起关闭。此时,仍在读取的客户端InputStream将收到套接字不再有效的通知,并引发该异常。您应该检查是否testfile.txt写入成功。可能没问题,尽管我不会让服务器如此突然地断开连接。我会让客户端正常关闭,或者在不活动后使客户端连接超时,因为Connection Reset在从 TCP 缓冲区读取所有数据之前,您可能会遇到该错误。(TCP 错误的通信速度往往更快。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java