Note that there are some explanatory texts on larger screens.

plurals
  1. POSocket: premature end of JPEG file
    text
    copied!<p>I'm trying to send an image file from a server to a client via a socket. <strong>The socket was previously used to send some strings from the server to the client</strong> (with buffered input/output streams). </p> <p>The trouble is the image file can't be received properly, with "Premature end of JPEG file" error.</p> <p>The server first sends the file size to the client, the client then creates a byte[] of that size, and starts to receive the file.</p> <p>Here are the codes:</p> <p>Server:</p> <pre><code> DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); //Send file size dos.writeInt((int) file.length()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] fileBytes = new byte[bis.available()]; bis.read(fileBytes); bis.close(); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); bos.write(fileBytes); bos.flush(); </code></pre> <p>Client:</p> <pre><code> DataInputStream dis = new DataInputStream(socket.getInputStream()); //Receive file size int size = dis.readInt(); BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); byte[] fileBytes = new byte[size]; bis.read(fileBytes, 0, fileBytes.length); </code></pre> <p>More interestingly, <strong>if I let server sleep for about 2 seconds between sending the file size and writing the byte[], then the image is received properly</strong>. I wonder if there's some kind of race condition between the server and the client</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload