0

I have developed a basic java client/server using sockets. Using PrintWriter, everything works as expected. But, if I change the server output method to DataOutputStream, the InputStream on the client is 0 length, and it eventually times out.

Server side

It works when I use (1):

bufferOut = new PrintWriter(new BufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);                  
bufferOut.println(response);

But not when I use (2):

bufferOut = new DataOutputStream(socket.getOutputStream());
bufferOut.write(response.getBytes("US-ASCII"));

The client has an InputStream length = 0

The only exceptions encountered are when the client times out and closes the socket - the server then throws a broken pipe exception.

Client side

DataInputStream in = new DataInputStream(socket.getInputStream());
String read = bufferIn.readLine();

What am I not understanding? Is there something missing? What else can I provide to help?

Edit

Updated client side:

DataInputStream dis = new DataInputStream(socket.getInputStream());
int length = dis.available();                   

// create buffer
byte[] buf = new byte[length];                  
// read the full data into the buffer
dis.readFully(buf);

Log.d(TAG,  "buffer length: "+buf.length);

// for each byte in the buffer
for (byte b:buf){
    // convert byte to char
    char c = (char)b;                      
    // append 
    message_string += c;
}

Still not getting data back with (2) - logcat buf.length = 0

Roy Hinkley
  • 10,111
  • 21
  • 80
  • 120
  • The `PrintWriter` will automatically flush the data while the `DataInputStream` will not, add a `bufferOut.flush()` call after you write something to the stream, see if that helps. Also `DataInputStream.readLine()` is deprecated, you should use some other read method. – Titus Jan 05 '16 at 19:06

1 Answers1

0

println() appends a line terminator. write() does not. readLine() blocks until a line terminator is read, or EOS or an exception occurs.

If you're using readLine() at one end, you should be using BufferedInputStream.readLine(),, and a Writer at the other end, not DataOutputStream.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • What should I use on the client - I need to handle raw ASCII – Roy Hinkley Jan 05 '16 at 19:40
  • If you're sending non-character data you should use `InputStream` and `OutputStream`. If you're in control of both ends you can use `readUTF()` and `writeUTF()` instead of lines. – user207421 Jan 05 '16 at 23:08