2013-09-06 3 views
0

서버에 한 번 연결하여 2 개의 요청을 만들어야합니다. 이 작업을 위해 'SocketChannel'을 사용하고 필요한 것을 할 수 없습니다.Java : 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 연결을 다시 사용하는 방법은 무엇입니까?

답변

2

HTTP 연결을 다시 사용하려면 HTTP/1.1 서버를 사용해야하며 GET에서이를 지정해야한다고 생각됩니다.

첫 번째 루프는 결과가 끝날 때까지 읽어야하며 스트림이 끝날 때까지 연결을 닫으면 다시 사용할 수 없기 때문에 읽어야합니다.