第一次寫,不好意思,有不對地方多多指出
在Java Socket 編程中,對 InputStream的read()=-1標明流結束,一般按照
- public byte[] getReqData(InputStream is){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try{
- int iR = is.read();
- while(iR != -1){
- baos.write(iR);
- iR = is.read();
- }
- }catch(Exception e){
- return null;
- }
- return baos.toByteArray();
- }
獲取byte
但是出現了一直等待現象,而在客戶端是本地發送測試的。。。跟蹤是在iR = is.read()時在讀完最后一個字節就阻塞了,繼續等-1的到來啊。。。。
網上也有很多對此的提問。
搜索了下,發現這個帖子討論的比較多:
http://ansonlai.iteye.com/blog/556287
樓主帖子和回復也很有幫助。不過俺還是不滿意,繼續搜索,測試,得以發現原因,在那個帖子回復如下:
在我的程序中同樣出現了這個問題,搜索到此。3樓的方案雖然解決了問題,仍然沒有說明問題所在。用中文搜索沒找到滿意解決,只得英文搜索,搜索到:http://stackoverflow.com/questions/611760/java-inputstream-read-blocking
其中有段話有啟發:It returns -1 if it's end of stream. If stream is still open (i.e. socket connection) but no data has reached the reading side (server is slow, networks is slow,...) the read() blocks.
最后發現其實有關 read()本身沒問題,而是client端沒有做好。
在socket.getOutputStream().write(data)后,嘗試socket.getOutputStream().close()。服務器端沒問題了,read()會返回-1咯。。。呵呵,但是(最怕但是),客戶端close OutputStream后等帶服務器的回應的InputSteam.read()出現了:socket closed Exception
最后發現Socket有 shutdownOutput()方法!哈哈,在客戶端write,flush后再調用shutdownOutput(),成了!后面的inputStream仍然可以。。。
當然,如果客戶端和服務器程序是各自開發,樓主及3樓的方法還是必要。
這次我碰到的問題其實說明這個現在還是普便存在的:本來用http實現通信的,用httpserver的httpExchange.getRequestBody()得到的InputStream處理就沒有出現這個問題。后來到現場才發現服務器的開發單位最終是用socket實現的通信,還專門提出了socket的頭6個字節表示長度,俺這么一寫,才發現對方可能也是碰到這個問題,采取了長度方法來處理。(我是在做服務器端simulator,同時也要做這個simulator的測試,所以客戶端simulator也做,沒聽糊塗吧:) )
shutdownOutput
public void shutdownOutput()
throws IOException
Disables the output stream for this socket. For a TCP socket, any previously written data will be sent followed by TCP's normal connection termination sequence. If you write to a socket output stream after invoking shutdownOutput() on the socket, the stream will throw an IOException.
也按照1樓同學的提示,對一個socket的先發一段,睡10秒,100秒再發后面一段,服務器都可以正常接收,客戶端也正常收到返回數據