public class AIOServer implements Runnable{
// static int PORT = 8080;
// static int BUFFER_SIZE = 1024;
// static String CHARSET = "utf-8"; //默认编码
// static CharsetDecoder decoder = Charset.forName(CHARSET).newDecoder(); //解码
private static Logger logger=LoggerFactory.getLogger("AIO server:");
private int port =7001;
private String host="127.0.0.1";
private AsynchronousServerSocketChannel server;
public AsynchronousServerSocketChannel getServer() {
return server;
}
public void setServer(AsynchronousServerSocketChannel server) {
this.server = server;
}
private InetSocketAddress serverAddress;
public AIOServer() {
serverAddress=new InetSocketAddress(port);
try {
server=AsynchronousServerSocketChannel.open();
server.bind(serverAddress);
} catch (IOException e) {
logger.info(e.toString());
}
}
public AIOServer(int port) {
this.port=port;
serverAddress=new InetSocketAddress(port);
try {
server=AsynchronousServerSocketChannel.open();
server.bind(serverAddress,1024);
} catch (IOException e) {
logger.info(e.toString());
}
}
public AIOServer(String host,int port) {
this.host=host;
this.port=port;
serverAddress=new InetSocketAddress(this.host,port);
try {
server=AsynchronousServerSocketChannel.open();
server.bind(serverAddress,1024);
} catch (IOException e) {
logger.info(e.toString());
}
}
private void listen() {
server.accept(this, new AcceptHandler());
}
private class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AIOServer>{
private Logger logger=LoggerFactory.getLogger("AcceptHandler:");
@Override
public void completed(AsynchronousSocketChannel result, AIOServer attachment) {
try {
logger.info("远程地址:" + result.getRemoteAddress());
//tcp各项参数
result.setOption(StandardSocketOptions.TCP_NODELAY, true);
result.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
result.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
if (result.isOpen()) {
logger.info("client.isOpen:" + result.getRemoteAddress());
ByteBuffer buffer = ByteBuffer.allocate(1024);
//buffer.clear();
result.read(buffer, result, new ReadHandler(buffer));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
attachment.getServer().accept(attachment, this);// 监听新的请求,递归调用。
}
}
@Override
public void failed(Throwable exc, AIOServer attachment) {
try {
exc.printStackTrace();
} finally {
}
}
}
private class ReadHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>{
private ByteBuffer buffer;
public ReadHandler(ByteBuffer buffer) {
this.buffer = buffer;
}
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
try {
if (result ==-1) { //连接断开
logger.info("连接断开.......");
attachment.close();
} else if (result == 0) {
logger.info("空数据"); // 处理空数据
} else {
// 读取请求,处理客户端发送的数据
buffer.flip();
byte[] read=new byte[result];
//("缓冲区: "+readCounter+" "+read.length);
buffer.get(read,0,read.length);
String expression=new String(read,"utf-8");
logger.info(expression);
//响应操作,服务器响应结果
buffer.flip();
attachment.write(buffer, attachment, new WriteHandler(buffer));
buffer.clear();
attachment.read(buffer, attachment, new ReadHandler(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
exc.printStackTrace();
try {
attachment.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class WriteHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>{
private ByteBuffer buffer;
public WriteHandler(ByteBuffer buffer) {
this.buffer=buffer;
}
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
buffer.clear();
logger.info("发送: "+result);
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
// exc.printStackTrace();
// try {
// server.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
@Override
public void run() {
listen();
while(true) {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
AIOServer server=new AIOServer();
ExecutorService exec=Executors.newCachedThreadPool();
exec.submit(server);
}
}
1、关键参数 channel buffer handler
a、AsyncchronousServerSocketChannel:
异步服务端套接字通道
b、 AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AIOServer> :
侦听事件注册类
c、ReadHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>:
套接字读事件注册类
d、WriteHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>:
套接字写事件注册类
2、工作流程
打开通道->绑定通道主机和端口->通道侦听并注册处理事件类
----->在侦听事件类中完成方法设置参数并注册读处理事件类