I want to create a simple multiple file transfer program using java socket.
server output:
I am server The server is listening... Client are connected Files Selected : 2 README.txt vcruntime140.dll Server Closed!
client output:
i am client Server are connected filecount : 2 filenames : README.txt
Exception in thread "main" java.io.EOFException at java.io.DataInputStream.readFully(Unknown Source) at java.io.DataInputStream.readLong(Unknown Source) at socket.client.main(client.java:32)
This is my server code! server is sender.
public static void main(String[] args) throws Exception {
System.out.println("i am server");
System.out.println("");
server = new ServerSocket(12345);
System.out.println("Server is listening...");
client = server.accept();
System.out.println("Client are connected");
dos = new DataOutputStream(client.getOutputStream());
dir = "C:\\Users\\Nitesh Rathi\\Downloads\\vcruntime140";
files = new File(dir).listFiles();
System.out.println("Files Selected : " + files.length);
dos.writeInt(files.length);
byte[] b = new byte[4096];
for (File file : files)
{
long length = file.length();
dos.writeLong(length);
String filename = file.getName();
dos.writeUTF(filename);
System.out.println(file.getName());
fis = new FileInputStream(file);
while (fis.read(b) != -1)
{
fis.read(b, 0, b.length);
dos.write(b, 0, b.length);
}
}
System.out.println("");
fis.close();
client.close();
server.close();
System.out.println("Server Closed!");
}
This is my client code! client is receiver.
public static void main(String[] args) throws Exception {
System.out.println("i am client");
System.out.println("");
soc = new Socket("localhost", 12345);
System.out.println("Server are connected");
dis = new DataInputStream(soc.getInputStream());
int filecount = dis.readInt();
File[] files = new File[filecount];
System.out.println("filecount : " + filecount);
byte[] b = new byte[1024];
for (int i=0;i<filecount;i++)
{
long filelength = dis.readLong();
String filename = dis.readUTF();
System.out.println("filenames : "+filename);
files[i] = new File(dirPath + "/" + filename);
fos = new FileOutputStream(files[i]);
for(int j = 0; j < filelength; j++)
{
fos.write(b);
dis.read(b);
}
}
System.out.println("data received!");
fos.flush();
fos.close();
soc.close();
System.out.println("client closed!");
}
I expect this output of the client: File count : 2 File names : README.txt vcruntime140.dll