我正在嘗試設(shè)置一個可以發(fā)送和接收文件的 java 程序。我知道這個網(wǎng)站上有類似的問題,但在閱讀這些內(nèi)容后我遇到了麻煩。我關(guān)注了這個視頻:https ://www.youtube.com/watch?v=WeaB8pAGlDw&ab_channel=Thecodersbay它在他的視頻中有效,我不確定我做錯了什么。第一個 java 文件運行得很好,但是當(dāng)我嘗試運行第二個時,我得到了這個錯誤: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)我嘗試使用其他一些端口,但這并沒有解決問題。這是我現(xiàn)在所擁有的:文件服務(wù)器文件: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 thingimport 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 }}我試圖發(fā)表很多評論,以便我能夠理解事情。提前致謝 :)
1 回答

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超10個贊
因此,Connection Reset
意味著套接字從另一端關(guān)閉。考慮到您的“服務(wù)器”在做什么,這是非常合乎邏輯的。
當(dāng)客戶端連接時,您的服務(wù)器正在接受連接,從文件中讀取最多 2002 個字節(jié),將其發(fā)送到客戶端并終止應(yīng)用程序。此時,套接字sr
將與應(yīng)用程序的其余資源一起關(guān)閉。此時,仍在讀取的客戶端InputStream
將收到套接字不再有效的通知,并引發(fā)該異常。
您應(yīng)該檢查是否testfile.txt
寫入成功。可能沒問題,盡管我不會讓服務(wù)器如此突然地斷開連接。我會讓客戶端正常關(guān)閉,或者在不活動后使客戶端連接超時,因為Connection Reset
在從 TCP 緩沖區(qū)讀取所有數(shù)據(jù)之前,您可能會遇到該錯誤。(TCP 錯誤的通信速度往往更快。)
添加回答
舉報
0/150
提交
取消