首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:如何重用SocketChannel

Java:如何重用SocketChannel
EN

Stack Overflow用户
提问于 2013-09-06 11:18:23
回答 1查看 592关注 0票数 0

我需要用一个连接到服务器的两个请求。我用“SocketChannel”来完成这个任务,我不能做我需要的事情。

代码语言:javascript
复制
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连接?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-06 11:40:08

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18656549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档