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?