[英]Exception with DataOutputStream but not PrintWriter
我已經開發了使用套接字的基本Java客戶端/服務器。 使用PrintWriter
,一切都會按預期進行。 但是,如果我將服務器輸出方法更改為DataOutputStream
,則客戶端上的InputStream
的長度為0,並且最終超時。
服務器端
當我使用(1)時,它可以工作:
bufferOut = new PrintWriter(new BufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);
bufferOut.println(response);
但是當我使用(2)時不是:
bufferOut = new DataOutputStream(socket.getOutputStream());
bufferOut.write(response.getBytes("US-ASCII"));
客戶端的InputStream
長度為0
遇到的唯一異常是當客戶端超時並關閉套接字時-服務器隨后拋出中斷的管道異常。
客戶端
DataInputStream in = new DataInputStream(socket.getInputStream());
String read = bufferIn.readLine();
我不明白什么? 缺少什么嗎? 我還能提供什么幫助?
編輯
更新的客戶端:
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;
}
仍然無法通過(2)取回數據-logcat buf.length = 0
println()
追加一個行終止符。 write()
沒有。 readLine()
阻塞,直到讀取行終止符,或者EOS或發生異常。
如果在一端使用readLine()
,則應在另一端使用BufferedInputStream.readLine(),
Writer
,而不是DataOutputStream.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.