import java.io.*; import java.net.*; class InetServe extends Thread { private Socket socket; private InputStream in; private PrintWriter out; private int timesAccessed; public InetServe (Socket s, int tA) throws IOException { socket = s; timesAccessed = tA; System.out.println("Serving: "+socket); in = socket.getInputStream(); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); start(); // Start the thread, calls run() } // Convert an array to an integer public static final int byteArrayToInt(byte[] b) { return (int) ( ((b[0] & 0xFF) << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + ( b[3] & 0xFF) ); } public void run() { byte[] b = new byte[1024]; // 1 KB block byte[] bInt = new byte[4]; // Integer in bytes String fileName; int fileNameSize=0; int fileSize=0; int fileSizeInKB=0; int sizeOfLastPart=0; try { // Get length of filename in.read(bInt); fileNameSize = byteArrayToInt(bInt); // Get length of file in.read(bInt); fileSizeInKB = byteArrayToInt(bInt); in.read(bInt); sizeOfLastPart = byteArrayToInt(bInt); // Read in filename in.read(b,0,fileNameSize); fileName = new String(b); FileOutputStream fOut = new FileOutputStream(fileName); System.out.println("File Name: " + fileName); System.out.println("File Size: " + (float)(fileSizeInKB*1024 + sizeOfLastPart)/1024 + " kB"); // Read in the data in 1 kB blocks System.out.print( "\nReceiving: "); for(int i = 0; i < fileSizeInKB; i ++) { in.read(b); fOut.write(b); // Write data to output file // Display the current percentage 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"); out.println("Okay"); } // Output the end of the file if needed if(sizeOfLastPart > 0) { byte[] bEnd = new byte[sizeOfLastPart]; in.read(bEnd); fOut.write(bEnd); } out.println("Okay"); System.out.println( "100%" ); fOut.close(); }catch (Exception e){ System.out.println("Caught unexpected exception\n"); } finally { try { socket.close(); } catch(IOException e) { System.out.println("Caught unexpected exception\n"); } } } } public class fileTransServer { static int PORT=0; // assign to next avalible Port. public static void main(String[] args) throws IOException { if (args.length == 1) { PORT=Integer.parseInt(args[0]); // assign to a given Port. } int timesAccessed = 0; // Create a Server Socket. ServerSocket s = new ServerSocket(PORT); InetAddress addrs= InetAddress.getLocalHost(); System.out.println("Server running on : "+ addrs + " ,Port "+s.getLocalPort()); try { while(true) { Socket socket = s.accept(); // Note: This is a blocking call try { new InetServe(socket, ++ timesAccessed); // Handle incoming client } catch(IOException e) { socket.close(); } } } finally { s.close(); } } }