[英]Unable to read data bytes from input stream in java tcp socket
在我的服務器代碼中,我向客戶端發送了不同的請求並返回響應,但是僅訪問了第一個讀取請求,在訪問第二個讀取語句期間,它無法讀取數據字節,我的代碼如下。
private static boolean Rt_Request(int id,Object client)throws Exception
{
int size=5;
byte[] buf=new byte[size];
char[] cbuf=new char[32];
int byteRead; Socket s=(Socket)client;
BufferedReader in1= new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintStream out=new PrintStream(s.getOutputStream());
try {
buf[0]=0x02;
buf[1]=0x09;
buf[2]=0x01;
buf[3]=0x00;
buf[4]=0x03;
Thread.sleep(5000);
out.write(buf, 0, 5);
} catch(Exception e) {
System.out.println("Error Occured...."+e);
}
byteRead=0;
while(byteRead!=1) {
try {
byteRead=in1.read(cbuf, 0, 1);// Have problem on this line,here I am unable to read data bytes.
for(int i=0;i<byteRead;i++)
{
System.out.println(cbuf[i]);
}
if(byteRead==0)
{
System.out.println("Breaking.....");
return false;
}
}
catch(Exception e) {
System.out.println("Error Occured...."+e);
return false;
}
}
return true;
} catch(Exception e) {
System.out.println("System is not Connected..."+e);
return false;
}
幾乎嘗試過所有未關閉的套接字,read.available();, read.fully(); 等。無法獲得解決方案。我已經在TimerTask類的run方法中編寫了此函數。 任何幫助將不勝感激
javadocs說BufferedReader#read(char [],int,int)返回:讀取的字符數;如果已到達流的末尾,則返回-1
因為你做
byteRead=in1.read(cbuf, 0, 1);
在
while(byteRead!=1)
更改為
while(byteRead != -1)
byteRead=in1.read(cbuf, 0, 1);
該行僅讀入一個值,並且由於您在進入for循環之前不會再次調用它,因此應該在標准輸出中獲得讀取值的1 println。
如果沒有可用數據,則底層InputStream
的read方法將阻塞(即掛起/等待)。
該方法將阻塞,直到輸入數據可用,檢測到文件結尾或引發異常為止。
我強烈懷疑是這種情況。 您可以通過在閱讀器上調用in1.ready()
進行檢查。
刷新輸出緩沖區
out.flush();
寫入字節后,否則它們可能會在本地緩沖。
read()
阻塞,直到至少有一個字節可用為止。 也許您沒有發送它,或者沒有正確刷新它,或者您可能在同一套接字上創建了多個BufferedReaders
。
NB bytesRead
read(cbuf, 0, 1).
成功read(cbuf, 0, 1).
后永遠不能為零read(cbuf, 0, 1).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.