• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Re-Reading from the stream...

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

Streams are behaving funny!!! i'll try to give you a gist of the problem instead of just blindly copy pasting the code...

I have,
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream in_raw = new DataInputStream(socket.getInputStream());

Somewhere in the code, in a while ( true ) loop i do this:-
while ( true ) {
String line = in.readLine();
if ( line.equals("aabbcc") )
break;
}

again; below i have another while ( true ) loop:-
while ( true ) {
for ( .. ; .. ; .. ) {
curr_byte = (byte)in_raw.read();
if ( curr_byte == -1 )
break;
}
}

Now, say i were to send the string 'aabbcc' from the other end using PrintWriter out = new PrintWriter(client.getOutputStream(), true); , in.readLine() does catch it but the problem is, so does (byte)in_raw.read(), so i end up reading byte values for the chars aabbcc again, which i dont want to. I guess when you read from a stream you automatically 'delete' contents of the stream however to make sure thats happening, i tried re initializing the in_raw, tried closing the in object but all in vain...

Does anyone know whats happening here?? Any fix for what I'm trying to do??

Thanks
Neville
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you use a BufferedReader, it reads a large block of bytes in advance, then gives those bytes out to you as you ask for them. (That's what "buffered" means.) Therefore the bytes that it's holding in its buffer are not available to your DataInputStream. Unexpected results, um, result.

So the short answer is, it's a bad idea to do that. Just have one stream that does all your reading. If you've got a protocol which makes that inconvenient, perhaps because you're mixing bytes with text, then that suggests the protocol should be revised too.
 
please buy this thing and then I get a fat cut of the action:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic