Java:如何重用SocketChannel

标签 java sockets 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 指定这一点。

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

关于Java:如何重用SocketChannel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18656549/

相关文章:

相同算法的 Java 与 C 版本

c - 套接字卡在 CLOSE_WAIT 状态

java - 在 SocketChannel 上通过 TCP 读取未定义字节数的流

.net - 高性能UDP服务.NET

java - SocketChannel 的超时不起作用

java.lang.Object 无法转换为 java.nio.channels.SocketChannel

java - UML 2.0 类图中是否允许包?

Java ArrayList 声明

java - 使用 Visual Studio Code 远程扩展运行 JavaFX

c - 如何安装xsock?