Java AIO 입문 실례

2983 단어 자바IOaiojava7
출처
 
자바 7 AIO 입문 인 스 턴 스, 우선 서버 구현:
서버 코드
SimpleServer:
 
public class SimpleServer {

    public SimpleServer(int port) throws IOException {
        final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));

        listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            public void completed(AsynchronousSocketChannel ch, Void att) {
                //        
                listener.accept(null, this);

                //       
                handle(ch);
            }

            public void failed(Throwable exc, Void att) {

            }
        });

    }

    public void handle(AsynchronousSocketChannel ch) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        try {
            ch.read(byteBuffer).get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byteBuffer.flip();
        System.out.println(byteBuffer.get());
        // Do something
    }
    
}

다음은 클 라 이언 트 구현:
클 라 이언 트 코드
SimpleClient:
public class SimpleClient {
    
    private AsynchronousSocketChannel client;
    
    public SimpleClient(String host, int port) throws IOException, InterruptedException, ExecutionException {
        this.client = AsynchronousSocketChannel.open();
        Future<?> future = client.connect(new InetSocketAddress(host, port));
        future.get();
    }
    
    public void write(byte b) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        byteBuffer.put(b);
        byteBuffer.flip();
        client.write(byteBuffer);
    }

}

간단 한 테스트 용례 를 써 서 서버 와 클 라 이언 트 를 달리 고 testServer () 를 먼저 실행 하고 testClient () 를 실행 합 니 다.
테스트 용례
AIOTest
 
public class AIOTest {
    
    @Test
    public void testServer() throws IOException, InterruptedException {
        SimpleServer server = new SimpleServer(7788);
        
        Thread.sleep(10000);
    }
    
    @Test
    public void testClient() throws IOException, InterruptedException, ExecutionException {
        SimpleClient client = new SimpleClient("localhost", 7788);
        client.write((byte) 11);
    }

}

비동기 이기 때문에 server 를 실행 할 때 동기 화 차단 이 발생 하지 않 았 습 니 다. 여기에 스 레 드 sleep () 를 추 가 했 습 니 다. 없 으 면 프로그램 이 바로 달 려 서 회수 합 니 다.

좋은 웹페이지 즐겨찾기