客户端代码
package test;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AIOClient {
private final AsynchronousSocketChannel client;
public AIOClient() throws Exception {
client = AsynchronousSocketChannel.open();
}
public void start() throws Exception {
client.connect(new InetSocketAddress("127.0.0.1", 8800), null, new CompletionHandler<Void, Object>() {
@Override
public void completed(Void result, Object attachment) {
try{
client.write(ByteBuffer.wrap("Hello".getBytes())).get();
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
final ByteBuffer byteBuffer = ByteBuffer.allocate(5);
client.read(byteBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println(result);
System.out.println(new String(byteBuffer.array()));
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
try{
Thread.sleep(Integer.MAX_VALUE);
}catch (Exception exception){
exception.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
new AIOClient().start();
}
}
服务端代码
package test;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AIOServer {
private void listen(int port) {
try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()) {
server.bind(new InetSocketAddress(port));
System.out.println("Server is listening on " + port);
ByteBuffer buff = ByteBuffer.allocateDirect(5);
server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
try {
buff.clear();
result.read(buff).get();
buff.flip();
// 把发过来的消息再返回回去
result.write(buff);
buff.flip();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
result.close();
;
server.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println("Server failed: " + exc);
}
});
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public static void main(String[] args){
int port = 8800;
AIOServer s = new AIOServer();
s.listen(port);
}
}