I am trying to transfer a binary from the server to the client in blocks of bytes at a time. However, I have a problem when it gets stuck in 8kb transfer. The file is usually larger than 1mb, and the byte array is 1024. I believe that it should do something with my while loop, since it does not close my connection. Any help? Thanks
Client
import java.io.*; import java.net.Socket; public class FileClient { public static void main(String[] argv) throws IOException { Socket sock = new Socket("localhost", 4444); InputStream is = null; FileOutputStream fos = null; byte[] mybytearray = new byte[1024]; try { is = sock.getInputStream(); fos = new FileOutputStream("myfile.pdf"); int count; while ((count = is.read(mybytearray)) >= 0) { fos.write(mybytearray, 0, count); } } finally { fos.close(); is.close(); sock.close(); } } }
Server
import java.net.*; import java.io.*; public class FileServer { public static void main(String[] args) throws IOException { ServerSocket servsock = new ServerSocket(4444); File myFile = new File("myfile.pdf"); FileInputStream fis = null; OutputStream os = null; while (true) { Socket sock = servsock.accept(); try { byte[] mybytearray = new byte[1024]; fis = new FileInputStream(myFile); os = sock.getOutputStream(); int count; while ((count = fis.read(mybytearray)) >= 0) { os.write(mybytearray, 0, count); } os.flush(); } finally { fis.close(); os.close(); sock.close(); System.out.println("Socket closed"); } } } }
source share