我正在尝试设置一个可以发送和接收文件的 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
}
}
我试图发表很多评论,以便我能够理解事情。
提前致谢 :)
拉莫斯之舞
相关分类