0

我需要通过一个与服务器的连接发出 2 个请求。我使用“SocketChannel”来完成这项任务,但我无法做我需要的事情。

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

在输出中,我只看到第一个请求的结果。任何异常都不会抛出。

如果我使用Socket,我会看到相同的结果。

如何重用 SocketChannel 连接?

4

1 回答 1

2

要重用 HTTP 连接,您需要使用 HTTP/1.1 服务器,我怀疑您需要让 GET 指定这一点。

您的第一个循环需要读取直到结果结束,而不是流结束,因为一旦连接关闭,您就无法重用它。

于 2013-09-06T11:40:08.193 回答