문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top