import java.net.*; import java.io.*; public class fileTransClient{ // Convert an integer to an array of bytes public static final byte[] intToByteArray(int value) { return new byte[]{ (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) }; } public static void main(String[] args) throws IOException { if (args.length != 3 && args.length != 4) { System.out.println("Usage: java ftpServer hostid port# fileName [transferName]"); System.exit(0); } String fileName = args[2]; String transferName; if(args.length == 3) transferName = fileName; else transferName = args[3]; try { InetAddress addr = InetAddress.getByName(args[0]); Socket socket = new Socket(addr, Integer.parseInt(args[1])); try { System.out.println("socket = " + socket); BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); OutputStream out = socket.getOutputStream(); // read from keyboard input DataInputStream myinput = new DataInputStream( new BufferedInputStream(System.in)); try { FileInputStream fIn = new FileInputStream(fileName); byte[] nameBytes = new byte[255]; int sizeOfLastPart; byte[] b = new byte[1024]; // First send out filename length and data length out.write(intToByteArray(transferName.length())); out.flush(); // Get the file's size and calculate the number of blocks File f = new File(fileName); int fileSizeInKB = (int)(f.length() / 1024); sizeOfLastPart = (int)(f.length() - (fileSizeInKB)*1024); // Send out the number of 1kB blocks // and then the number of bytes for the last black out.write(intToByteArray(fileSizeInKB)); out.flush(); out.write(intToByteArray(sizeOfLastPart)); out.flush(); System.out.println("File Length: " + (float)f.length() / 1024 + " KB"); nameBytes = transferName.getBytes(); out.write(nameBytes); out.flush(); // Write it out in 1kb blocks int i; System.out.print( "\nSending: "); for(i = 0; i < fileSizeInKB; i ++ ) { fIn.read(b); // Read 1kB out.write(b); out.flush(); // Print out the percentage completed System.out.print(i*100/fileSizeInKB + "%"); System.out.flush(); if(i*100/fileSizeInKB < 10) System.out.print("\b\b"); else System.out.print("\b\b\b"); in.readLine(); // Receive ack } // Output the end of the data if needed byte bEnd[] = new byte[sizeOfLastPart]; if(sizeOfLastPart > 0) { fIn.read(bEnd); out.write(bEnd, 0, sizeOfLastPart); out.flush(); } String strout = in.readLine(); // Receive last ack System.out.println( "100%"); }catch (IOException e){ e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } finally { socket.close(); } } catch(UnknownHostException e){ System.err.println("Can't find host"); System.exit(1); } catch (SocketException e){ System.err.println("Can't open socket"); e.printStackTrace(); System.exit(1); } } }