Java AIO入门实例源码教程。NIO.2中引入了新的异步通道的概念,并提供了异步Socket通道的实现。阻塞式的Socket通道的使用方式都是同步进行的,调用者会处于阻塞状态;费阻塞Socket通道的实现方式则是依靠选择器(select)来完成。异步通道一般提供两种使用方式:一种是通过Java同步工具包中的java.util.concurrent.Future类的对象来表示异步操作的结果;另一种是在操作时传入一个java.nio.channels.CompletionHandler接口实现对象来作为操作完成时的回调方法。这两种使用的区别在于调用者通过何种方式来使用异步的结果。在使用Future类对象时,要求调用者在合适的时机显式地通过Future类对象的get方法来得到实际的操作结果;而在使用CompletionHandler接口时,实际的调用结果作为回调方法的参数来给出。
Java7 AIO入门实例,首先是服务端实现:
服务端代码
SimpleServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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(),如果没有的话,程序会直接跑完回收掉。