2013-03-05 25 views
0

我想用套接字發出http請求,因爲我想測試一下我可以創建我的服務器的套接字數量。所以我使用OutputStreamInputStream從我的服務器寫入和讀取。但在第一個響應之後,我無法再從輸入流中讀取數據。你知道如何在不關閉套接字的情況下讀取第二個響應?
這裏是我的代碼:如何重用java.net.socket中的inputstream?

Socket socket = new Socket(); 
socket.connect(new InetSocketAddress(address, 80), 1000); 
socket.setSoTimeout(25*1000); 

OutputStream os = socket.getOutputStream();   
os.write(getRequest(host)); // some request as bytearray, it has Connection: Keep-Alive in the header 
os.flush(); 

InputStream is = socket.getInputStream(); 
BufferedInputStream bis = new BufferedInputStream(is); 

String response = IOUtils.toString(bis); 
System.out.println("RESPONSE = \n" + response); // this works fine 

os.write(getRequestBodyBa()); // send another request, i can see it sent to server with wireshark 
os.flush(); 

// try to read again but it always return empty string    
response = IOUtils.toString(bis); // how to read the second response????? 
System.out.println("RESPONSE = \n" + response);   

os.close(); 
is.close(); 
socket.close(); 

感謝。

回答

1

我相信HTTP標準是關閉每個響應後的連接,除非請求有Connection header set to keep-alive

+0

但是OP正在使用一個套接字,你怎麼知道他在使用HTTP呢? – Carlo 2013-03-05 17:10:12

+0

那麼,我猜如果「服務器」不是一個Web服務器,那麼我的答案不適用。 – CodeChimp 2013-03-05 17:15:12

+0

我使用Connection:Keep-Alive在標題中發送http請求。 – 2013-03-05 17:18:03

1

IOUtils.toString(InputStream)將流讀取到EOS,因此下次無法讀取任何內容。不要使用它。您需要解析響應頭,確定是否存在Content-Length頭,如果是這樣的話,請正確讀取正文中的許多字節;如果沒有Content-Length頭部(並且沒有分塊),則連接在主體之後關閉,因此您無法發送第二個命令;等等等等。它是無止境的。不要爲此使用Socket:使用HTTP URLURLConnection.

+0

感謝您的回覆。我會嘗試並讓你知道。你知道一種方法來控制通過HTTPURLConnnection或URLConnection緩衝的底層套接字的數量嗎?我想控制它來測試我的服務器。 – 2013-03-06 07:41:19

+0

如果在使用每個URLConnection後調用disconnect(),則不應該有任何連接池。 – EJP 2013-03-06 11:21:58

+0

@CodeChimp你的評論屬於問題,而不是在這裏。 – EJP 2013-03-06 20:24:44

相關問題