AIOServer.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package cn.hhj.aio;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.AsynchronousChannelGroup;
  6. import java.nio.channels.AsynchronousServerSocketChannel;
  7. import java.nio.channels.AsynchronousSocketChannel;
  8. import java.nio.channels.CompletionHandler;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11. /**
  12. * AIO服务端
  13. */
  14. public class AIOServer {
  15. private final int port;
  16. public static void main(String args[]) {
  17. int port = 8000;
  18. new AIOServer(port);
  19. }
  20. public AIOServer(int port) {
  21. this.port = port;
  22. listen();
  23. }
  24. private void listen() {
  25. try {
  26. ExecutorService executorService = Executors.newCachedThreadPool();
  27. AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
  28. //开门营业
  29. //工作线程,用来侦听回调的,事件响应的时候需要回调
  30. final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup);
  31. server.bind(new InetSocketAddress(port));
  32. System.out.println("服务已启动,监听端口" + port);
  33. //准备接受数据
  34. server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>(){
  35. final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
  36. //实现completed方法来回调
  37. //由操作系统来触发
  38. //回调有两个状态,成功
  39. public void completed(AsynchronousSocketChannel result, Object attachment){
  40. System.out.println("IO操作成功,开始获取数据");
  41. try {
  42. buffer.clear();
  43. result.read(buffer).get();
  44. buffer.flip();
  45. result.write(buffer);
  46. buffer.flip();
  47. } catch (Exception e) {
  48. System.out.println(e.toString());
  49. } finally {
  50. try {
  51. result.close();
  52. server.accept(null, this);
  53. } catch (Exception e) {
  54. System.out.println(e.toString());
  55. }
  56. }
  57. System.out.println("操作完成");
  58. }
  59. @Override
  60. //回调有两个状态,失败
  61. public void failed(Throwable exc, Object attachment) {
  62. System.out.println("IO操作是失败: " + exc);
  63. }
  64. });
  65. try {
  66. Thread.sleep(Integer.MAX_VALUE);
  67. } catch (InterruptedException ex) {
  68. System.out.println(ex);
  69. }
  70. } catch (IOException e) {
  71. System.out.println(e);
  72. }
  73. }
  74. }