繁体   English   中英

如何重用java.net.socket中的inputstream?

[英]How to reuse inputstream from java.net.socket?

我想用socket创建http请求,因为我想测试我可以创建服务器的插槽数量。 所以我使用OutputStreamInputStream从我的服务器写入和读取。 但是在第一次响应之后我无法再次从输入流中读取。 你知道如何在不关闭套接字的情况下读取第二个响应吗?
这是我的代码:

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();

谢谢。

我相信HTTP标准是在每次响应后关闭连接,除非请求将Connection标头设置为keep-alive

IOUtils.toString(InputStream)将流读取到EOS,因此下次无法读取任何内容。 不要使用它。 您需要解析响应头,确定是否有Content-Length头,如果是这样,请读取正确的那个字节; 如果没有Content-Length标头(并且没有分块),则在主体之后关闭连接,因此您无法发送第二个命令; 等等等。这是无止境的。 不要使用Socket :使用HTTP URLURLConnection.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM