Reputation: 1412
I need to make 2 requests with one connection to server. I use 'SocketChannel' for this task and I can't do what I need.
public static void main(){
ByteBuffer in = null;
ByteBuffer out = null;
SocketChannel socket = null;
try {
socket = SocketChannel.open();
socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
socket.connect(new InetSocketAddress("192.168.150.128", 80));
// init buffers
in = ByteBuffer.allocate(1024);
out = ByteBuffer.allocate(1024);
// write to socket
String request = "GET /pgu.mos.ru/common/css/carousel/carousel.css\r\nHost: 192.168.150.128\r\n";
out.clear();
out.put(request.getBytes());
out.flip();
while (out.hasRemaining()) {
socket.write(out);
}
out.clear();
// read from socket
int count;
in.clear();
while ((count = socket.read(in)) != -1) {
in.flip();
while (in.hasRemaining()) {
System.out.print((char)in.get());
}
in.clear();
}
// write to socket (second request)
request = "GET /pgu.mos.ru/common/js/base/main/slider.js\r\nHost: 192.168.150.128\r\n";
out.clear();
out.put(request.getBytes());
out.flip();
while (out.hasRemaining()) {
socket.write(out);
}
out.clear();
// read from socket (second response)
in.clear();
while ((count = socket.read(in)) != -1) {
in.flip();
while (in.hasRemaining()) {
System.out.print((char)in.get());
}
in.clear();
}
Thread.sleep(10000);
socket.close();
} catch (IOException | InterruptedException ex) {
System.out.println(ex.getMessage());
}
}
In output I see only results from first request. Any exceptions do not throws.
If I use Socket
I see the same.
How to reuse SocketChannel connection?
Upvotes: 0
Views: 644
Reputation: 533530
To reuse a HTTP connection you need to use a HTTP/1.1 server and I suspect you need to make the GET specify this.
You first loop needs to read until the end of the result, not the end of the stream because once the connection is closed you can't reuse it.
Upvotes: 2