So, I have a simple client/server program that used to send a String across the open connection using writeUTF and readUTF. So everything was working fine where I could send multiple Strings and then they were printed out on the server side one by one. To my dismay, it turned out that I could not use the writeUTF, and instead am now sending the strings like so:
(that is in a loop to send multiple Strings of course)
So, the question is, what would be the equivalent method of readUTF on the server side to read the Strings being sent as bytes? So far, I've tried a few methods like using readFully() and using a BufferedReader as well, but I haven't found anyway to reproduce the readUTF() method which was able to read each string one by one. Both of the other methods I tried seem to read the stream of data in until it stops, so I end up getting all the Strings as a single String in the end (like they are all one right after another), and I am only done once all the Strings have been sent and am unable to print out each String as it gets received (there is a 1-second delay between sending each String on the client-side). Any ideas?
Before each writeBytes(), do a writeInt() where you send the size of the byte array you're about to send (you'd have to break your code into two lines and use a temp variable ot hold the array, so you could check the size of the array you were about to send). Then on the other end, do a readInt() to get the byteCount, and then just read that many bytes, convert to a String, display, and repeat.
If you are using BufferedReader to read incoming data, then you may write "\n" character to indicate end of line/word so readLine() returns a string as soon as it encounters this "\n".
And, you would probably want to use "UTF-8" instead of "US-ASCII" for converting strings to bytes and back again.
Author of <a href="http://www.newsinjector.com" target="_blank" rel="nofollow">NewsInjector</a>
Joined: Jan 27, 2004
OK, both seem like good solutions, however, I don't think I can use either because the server I am using is actually just a unit test stub, whereas the actual application that will be receiving the messages will not be able to deal with either a readInt() call before or the "\n" character. HOWEVER, I do frame each String with the SOH and ETX ASCII characters, so perhap on the server-side (the test stub) I could do something with those? Or maybe NOT use the BufferedReader and instead go back to a DataInputStream and read each byte individually until I find the byte for /\0? I appreciate the help. [ June 27, 2008: Message edited by: Eric Chang ]
Joined: Jan 27, 2004
Nevermind, I figured it out. The solutions you both gave sparked me to think about just using readByte and then reading each byte into an ArrayList until I reach the ETX ASCII character (byte = 3), and then printing out what I have. Thanks again!