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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.