AIOdemo源码

server:

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
39
40
41
42
43
package com.test.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
public class AIOServer {
public AIOServer(int port) throws IOException{
final AsynchronousServerSocketChannel listener=AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
listener.accept(null,new CompletionHandler<AsynchronousSocketChannel,Void>(){

@Override
public void completed(AsynchronousSocketChannel ch, Void attachment) {
listener.accept(null, this);//接受下一个链接
try {
handler(ch);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void failed(Throwable exc, Void attachment) {
System.out.println("AIo失败!");
}

});
}
//真正逻辑处理
public void handler(AsynchronousSocketChannel ch) throws Exception, ExecutionException{
ByteBuffer bytebuffer=ByteBuffer.allocate(32);
ch.read(bytebuffer).get();
bytebuffer.flip();
System.out.println("服务端接受数据"+new String(bytebuffer.array()));
}
public static void main(String[] args) throws Exception {
AIOServer server =new AIOServer(7080);
System.out.println("监听端口7080");
Thread.sleep(10000);
}
}

client:

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
package com.test.nio;

/**
* Created by lifei on 16/11/9.
*/
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;
public class AIOClient {
private AsynchronousSocketChannel client=null;
public AIOClient(String host,int port) throws Exception{
client =AsynchronousSocketChannel.open();
Future<?> future=client.connect(new InetSocketAddress(host,port));
System.out.println("返回结果:"+future.get());
}
public void write(byte[] b){
ByteBuffer bytebuffer=ByteBuffer.allocate(32);
bytebuffer.put(b);
bytebuffer.flip();
client.write(bytebuffer);
}
public static void main(String[] args) throws Exception {
AIOClient client=new AIOClient("localhost",7080);
client.write("hello ...".getBytes());
}
}