관리자 글쓰기
[NIO]TCP 비동기 채널 - 비동기 소켓 채널
2017. 1. 5. 22:06 - 개발 새발

-open() : 기본 비동기 채널에 포함되는 비동기 소켓 채널을 얻기 위한 방법


AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open();


-open(AsynchronousChannelGroup) : 별도로 비동기 채널 그룹을 생성하고 여기에 포함되는 비동기 소켓 채널을 얻기 위한 방법


AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(Runtime.getRuntime().availableProcessors(), Executors.defaultThreadFactory());

AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(channelGroup);


- 소켓 닫기


asynchronousSocketChannel.close();


- 연결


connect(SocketAddress remote, A attachment , CompletionHandler<Void, A> handler);


ex) asynchronousSocketChannel.connect(new InetSocketAddress(5001), Void , new CompletionHandler<Void, Void>(){


public void completed(Void result, Void attachment){

//연결 성공후 실행할 코드

}


public void failed(Throwable e, Void attachment){

//연결 실패후 실행할 코드

}

});



- 통신


read(ByteBuffer dst, A attachement, CompletionHandler<Integer, A> handler);

write(ByteBuffer dst, A attachement, CompletionHandler<Integer, A> handler);


ex) asynchronousSocketChannel.read(byteBuffer, attachment, new CompleteHandler<Integer, A>(){


public void comleted(Integer result, A attachment){


//받은 데이터를 처리하는 코드

asynchronousSocketChannel.read(byteBuffer, attachement, this);

}


public void failed(Throwable e, A attachement){

//실패된 경우의 실행할 코드

}

});


asynchronousSocketChannel.write(byteBuffer, attachment, new CompleteHandler<Integer, A>(){


public void comleted(Integer result, A attachment){

//성공할 경우의 실행할 코드

}


public void failed(Throwable e, A attachement){

//실패된 경우의 실행할 코드

}

});



2017/01/05 - [코딩/Java] - [NIO]TCP 비동기 채널 - 비동기 소켓 채널