Search code examples
javaserversocket

Java getInputStream Read not Exiting


Hi I have created a server socket for reading byte array from socket using getInputStream, But getInputStream.read is not exiting after endof data reaches. Below is my code.

 class imageReciver extends Thread {
    private ServerSocket serverSocket;
    InputStream in;

    public imageReciver(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
   }


    public void run()
   {
     Socket server = null;
     server = serverSocket.accept();
     in = server.getInputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buffer[] = new byte[1024];

    while(true){
    int s = 0;
    s = in.read(buffer); //Not exiting from here
    if(s<0) break;
    baos.write(buffer, 0, s);
    }
    server.close();     
    return;
  } 
 }    

From the client if I sent 2048 bytes, the line in.read(buffer) should return -1 after reading two times, but it waiting there to read for the third time. How can I solve this ? Thanks in advance....


Solution

  • Your server will need to close the connection, basically. If you're trying to send multiple "messages" over the same connection, you'll need some way to indicate the size/end of a message - e.g. length-prefixing or using a message delimiter. Remember that you're using a stream protocol - the abstraction is just that this is a stream of data; it's up to you to break it up as you see fit.

    See the "network packets" in Marc Gravell's IO blog post for more information.

    EDIT: Now that we know that you have an expected length, you probably want something like this:

    int remainingBytes = expectedBytes;
    while (remainingBytes > 0) {
        int bytesRead = in.read(buffer, 0, Math.min(buffer.length, remainingBytes));
        if (bytesRead < 0) {
            throw new IOException("Unexpected end of data");
        }
        baos.write(buffer, 0, bytesRead);
        remainingBytes -= bytesRead;
    }
    

    Note that this will also avoid overreading, i.e. if the server starts sending the next bit of data, we won't read into that.