title: Send a stream of images using ImageIO?
body: <p>I have a ServerSocket and a Socket set up so the ServerSocket sends a stream of images using ImageIO.write(....) and the Socket tries to read them and update a JFrame with them. So I wondered if ImageIO could detect the end of an image. (I have absolutely no knowledge of the JPEG format, so I tested it instead)</p>
  
  <p>Apparently, not.</p>
  
  <p>On the server side, I sent images continuously by using ImageIO.write(...) in loop with some sleeping in between. On the client side, ImageIO read the first image no problem, but on the next one it returned null. This is confusing. I was expecting it to either block on reading the first image (because it thinks the next image is still part of the same image), or succeed at reading all of them (because it works). What is going on? It looks like ImageIO detects the end of the first image, but not the second one. (The images, by the way, are similar to each other roughly) Is there an easy way to stream images like this or do I have to make my own mechanism that reads the bytes into a buffer until it reaches a specified byte or sequence of bytes, at which point it reads the image out of the buffer?</p>
  
  <p>This is the useful part of my server code:</p>
  
  <pre><code>        while(true){
              Socket sock=s.accept();
              System.out.println("Connection");
              OutputStream out=sock.getOutputStream();
              while(!socket.isClosed()){
                  BufferedImage img=//get image
                  ImageIO.write(img, "jpg", out);
                  Thread.sleep(100);
              }
              System.out.println("Closed");
          }
  </code></pre>
  
  <p>And my client code:</p>
  
  <pre><code>        Socket s=new Socket(InetAddress.getByName("localhost"), 1998);
          InputStream in=s.getInputStream();
          while(!s.isClosed()){
              BufferedImage img=ImageIO.read(in);
              if(img==null)//this is what happens on the SECOND image
              else // do something useful with the image
          }
  </code></pre>