簡體   English   中英

Java:如何重用SocketChannel

[英]Java: how to reuse SocketChannel

我需要通過一個連接到服務器發出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連接?

要重用HTTP連接,您需要使用HTTP / 1.1服務器,我懷疑您需要讓GET指定它。

您的第一個循環需要讀取直到結果的結尾,而不是流的結束,因為一旦連接關閉,您就無法重用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM