Java AIO 입문 실례
자바 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 () 를 추 가 했 습 니 다. 없 으 면 프로그램 이 바로 달 려 서 회수 합 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.