serversocket - Java getInputStream Read not Exiting -


hi have created server socket reading byte array socket using getinputstream, getinputstream.read not exiting after endof data reaches. below 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 here     if(s<0) break;     baos.write(buffer, 0, s);     }     server.close();          return;   }   }     

from client if sent 2048 bytes, line in.read(buffer) should return -1 after reading 2 times, waiting there read third time. how can solve ? in advance....

your server need close connection, basically. if you're trying send multiple "messages" on same connection, you'll need way indicate size/end of message - e.g. length-prefixing or using message delimiter. remember you're using stream protocol - abstraction stream of data; it's break see fit.

see "network packets" in marc gravell's io blog post more information.

edit: know have expected length, want 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 avoid overreading, i.e. if server starts sending next bit of data, won't read that.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -