I am trying to set up a java program that would send and receive a file.
I know there are similar things for this problem on this website, but I was having trouble after reading those.
I followed this video: https://www.youtube.com/watch?v=WeaB8pAGlDw&ab_channel=Thecodersbay
It worked in his video, and I am not sure what I did wrong. The first java file runs just fine, but when I try to run the second I get this error:
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)
I tried using some other ports, but that did not solve the problem.
Here is what I have right now:
The fileserver file:
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
}
}
This is the client file:
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
}
}
I tried to comment a lot so that I can make sense of things.
Thanks in advance :)