I am making a programe based on socket programing in which client can download one of the listed books from server. I have come up with this code but the problems with it are:
1) It doesnt downloads pdf file greater than 1MB.
2) It allows client to download 1 file only and then the connection is closed.
I want the client to be able to download as many files as he/she wants.
Please suggest improvements.
CLIENT CODE:
int filesize=10223860;
int bytesRead;
int currentTot = 0;
Socket socket = new Socket("127.0.0.1",15123);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
System.out.println("Select one book to download: ");
System.out.println("1) 1.pdf ");
System.out.println("2) 2.pdf ");
String opt;
opt = inFromUser.readLine();
outToServer.writeBytes(opt + '\n');
FileOutputStream fos = new FileOutputStream("copy"+opt);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do
{
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
}
while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
SERVER CODE:
ServerSocket serverSocket = new ServerSocket(15123);
Socket socket = serverSocket.accept();
System.out.println("Connection created successfully!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String n;
n = in.readLine();
File transferFile = new File (n);
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending File \""+n+"\"...");
os.write(bytearray,0,bytearray.length);
os.flush();
System.out.println("File transfer complete");
socket.close();