I'm trying to write a java program to transfer files over a network from one device to another using Sockets
. So I have two classes namely Server
and Client
to handle the program IO. I'm using FileInputStream
to read the bytes of a local file into Client
and Socket's OutputStream
to send the read bytes to the Server
. Here's
Code snippet of
class Client
:
int read;
System.out.print("Enter name of file to send : ");
String fileName = br.readLine();
File file = new File(fileName);
if(!file.exists()) {
LISTENER.log(fileName + "does not exists."); // Exception Logging
throw new IOException("File not found : " + fileName);
}
String parts[] = fileName.split("\\.");
String ext = parts[parts.length-1]; // Extracts the file extension
PrintWriter pw = new PrintWriter(sock.getOutputStream());
InputStream is = new FileInputStream(file);
pw.println(ext); // Sends file extension to the socket output stream
pw.flush();
while((read = is.read()) != -1) {
os.write(read); // Sends read bytes to the socket output stream
os.flush();
}
EXPLAINATION: So here I tried to get the file name and make a File object file
. String ext
extracts out the file extension and sends it to the Server
through PrintWriter
(so that at receiver end, it may create the file of the known extension). After that, InputStream is
reads the file bytes and without buffering them into the class Client
(for better performance), sends the read bytes directly through the socket OutputStream os
.
Code snippet of
class Server
:
String ext; int read;
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
while(running) {
ext = br.readLine(); // reads the file extension sent from client
if(ext == null)
throw new NullPointerException("File name provided does not have any specified extention");
broadcast(ext); // sends the file extension back to all clients
while((read = is.read()) != -1) {
broadcast(read); // sends the read bytes to all clients
}
}
EXPLAINATION: Here, Socket's InputStream Reader
reads the first line which contains the file extension passed by Client
through PrintWriter
.
broadcast(String)
method is used to send the extension back to all Client
implementations through PrintWriter
. Then the bytes of File are read by the Socket's InputStream is
read()
method till it returns -1(end of stream). broadcast(int)
sends the read bytes back to all Client
implementations.
PROBLEM:
The class Server
's InputStream is not reading all the bytes sent from class Clients
's OutputStream and as a result it's stuck in the while((read = is.read()) != -1)
loop because the stream never returned -1.
I tried to find the solution as to why the InputStream is not reading all bytes, but everywhere it was mentioned to use read(byte[],int,int)
and not read()
. But my question is why. Why InputStream is not reading all the bytes and why -1 is never returned in this case?