Netty之NIO入门(二)

小咪咪 2023-03-01 05:51 283阅读 0赞

文章目录

    • BIO
      • `思考`
    • NIO
        • 分析
    • NIO2.0 (AIO)
    • 最后

BIO

下图的通信模型图来熟悉下BIO的服务端通信模型:采用BIO通信模型的服务端,通常由一个独立的 Acceptor线程负责监听客户端的连接,它接收到客户端连接请求之后为每个客户端创建一个新的线程进行链路处理,处理完成之后,通过输出流返回应答给客户端,线程销毁。这就是典型的一请求一应答通信模型。
在这里插入图片描述
该模型最大的问题就是缺乏弹性伸缩能力,当客户端并发访问量增加后,服务端的线程个数和客户端并发访问数呈1:1的正比关系,由于线程是Java虚拟机非常宝贵的系统资源,当线程数膨胀之后,系统的性能将急剧下降,随着并发访问量的继续增大,系统会发生线程堆栈溢出、创建新线程失败等问题,并最终导致进程宕机或者僵死,不能对外提供服务。

同步阻塞式/O创建的 Time Server源码分析

  1. package main.com.phei.netty.bio;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.Socket;
  7. public class TimeClient {
  8. /** * @param args */
  9. public static void main(String[] args) {
  10. int port = 8080;
  11. if (args != null && args.length > 0) {
  12. try {
  13. port = Integer.valueOf(args[0]);
  14. } catch (NumberFormatException e) {
  15. // 采用默认值
  16. }
  17. }
  18. Socket socket = null;
  19. BufferedReader in = null;
  20. PrintWriter out = null;
  21. try {
  22. socket = new Socket("127.0.0.1", port);
  23. in = new BufferedReader(new InputStreamReader(
  24. socket.getInputStream()));
  25. out = new PrintWriter(socket.getOutputStream(), true);
  26. out.println("QUERY TIME ORDER");
  27. System.out.println("Send order 2 server succeed.");
  28. String resp = in.readLine();
  29. System.out.println("Now is : " + resp);
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. } finally {
  33. if (out != null) {
  34. out.close();
  35. out = null;
  36. }
  37. if (in != null) {
  38. try {
  39. in.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. in = null;
  44. }
  45. if (socket != null) {
  46. try {
  47. socket.close();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. socket = null;
  52. }
  53. }
  54. }
  55. }

以上是服务端,默认设置监听端口8080,然后通过一个死循环监听客户端连接,如果没有客户端连接就会阻塞在accept上。 当有新的客户端接入的时候,执行代码34行,以 Socket为参数构造 Timeserverhandler对象, Time Serverhandler是一个 Runnable,使用它为构造函数的参数创建一个新的客户端线程处理这条 Socket链路。下面我们继续分析 Timeserverhandler的代码。

  1. package main.com.phei.netty.bio;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.Socket;
  7. public class TimeServerHandler implements Runnable {
  8. private Socket socket;
  9. public TimeServerHandler(Socket socket) {
  10. this.socket = socket;
  11. }
  12. /* * (non-Javadoc) * * @see java.lang.Runnable#run() */
  13. @Override
  14. public void run() {
  15. BufferedReader in = null;
  16. PrintWriter out = null;
  17. try {
  18. in = new BufferedReader(new InputStreamReader(
  19. this.socket.getInputStream()));
  20. out = new PrintWriter(this.socket.getOutputStream(), true);
  21. String currentTime = null;
  22. String body = null;
  23. while (true) {
  24. body = in.readLine();
  25. if (body == null) {
  26. break;
  27. }
  28. System.out.println("The time server receive order : " + body);
  29. currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
  30. System.currentTimeMillis()).toString() : "BAD ORDER";
  31. out.println(currentTime);
  32. }
  33. } catch (Exception e) {
  34. if (in != null) {
  35. try {
  36. in.close();
  37. } catch (IOException e1) {
  38. e1.printStackTrace();
  39. }
  40. }
  41. if (out != null) {
  42. out.close();
  43. out = null;
  44. }
  45. if (this.socket != null) {
  46. try {
  47. this.socket.close();
  48. } catch (IOException e1) {
  49. e1.printStackTrace();
  50. }
  51. this.socket = null;
  52. }
  53. }
  54. }
  55. }

这一段拿到socket的输入流然后读取内容,如果是QUERY TIME ORDER就把时间写入到一个输出流返回给客户端。

  1. package main.com.phei.netty.bio;
  2. import java.io.IOException;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. public class TimeServer {
  6. /** * @param args * @throws IOException */
  7. public static void main(String[] args) throws IOException {
  8. int port = 8080;
  9. if (args != null && args.length > 0) {
  10. try {
  11. port = Integer.valueOf(args[0]);
  12. } catch (NumberFormatException e) {
  13. // 采用默认值
  14. }
  15. }
  16. ServerSocket server = null;
  17. try {
  18. server = new ServerSocket(port);
  19. System.out.println("The time server is start in port : " + port);
  20. Socket socket = null;
  21. while (true) {
  22. socket = server.accept();
  23. new Thread(new TimeServerHandler(socket)).start();
  24. }
  25. } finally {
  26. if (server != null) {
  27. System.out.println("The time server close");
  28. server.close();
  29. server = null;
  30. }
  31. }
  32. }
  33. }

运行结果如下:
在这里插入图片描述

在这里插入图片描述
总结
BIO主要的问题在于每当有一个新的容户端请求接入时,服务端必须创建一个新的线程处理新接入的客户端链路,一个线程只能处理一个客户端连接。在高性能服务器应用领域,往往需要面向成千上万个客户端的并发连接,这种模型显然无法满足高性能、高并发接入的场景。

思考

我们启动一个服务端,然后阻塞在那里,这个时候来了很多连接,然后服务端起了很多线程处理,这看上去没什么问题,而再仔细思考下,我们的主线程其实大部分时间是空闲的(accept阻塞在那),如下图所示:
在这里插入图片描述
那么问题来了,我们能不能把另开线程里面执行的东西放到主线程里面执行,因为线程资源是很稀缺的,也就是多个线程里面的任务在主线程里面执行,也就是主线程被重复使用了,也就是多路复用,也就出现了我们的NIO

NIO

上代码:

  1. package main.com.phei.netty.nio;
  2. public class TimeClient {
  3. public static void main(String[] args) {
  4. int port = 8080;
  5. if (args != null && args.length > 0) {
  6. try {
  7. port = Integer.valueOf(args[0]);
  8. } catch (NumberFormatException e) {
  9. // 采用默认值
  10. }
  11. }
  12. new Thread(new TimeClientHandler("127.0.0.1", port), "TimeClient-001")
  13. .start();
  14. }
  15. }
  16. package main.com.phei.netty.nio;
  17. public class TimeServer {
  18. public static void main(String[] args) {
  19. int port = 8080;
  20. if (args != null && args.length > 0) {
  21. try {
  22. port = Integer.valueOf(args[0]);
  23. } catch (NumberFormatException e) {
  24. // 采用默认值
  25. }
  26. }
  27. MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
  28. new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();
  29. }
  30. }
  31. package main.com.phei.netty.nio;
  32. import java.io.IOException;
  33. import java.net.InetSocketAddress;
  34. import java.nio.ByteBuffer;
  35. import java.nio.channels.SelectionKey;
  36. import java.nio.channels.Selector;
  37. import java.nio.channels.SocketChannel;
  38. import java.nio.charset.StandardCharsets;
  39. import java.util.Iterator;
  40. import java.util.Set;
  41. public class TimeClientHandler implements Runnable {
  42. private String host;
  43. private int port;
  44. private Selector selector;
  45. private SocketChannel socketChannel;
  46. private volatile boolean stop;
  47. public TimeClientHandler(String host, int port) {
  48. this.host = host == null ? "127.0.0.1" : host;
  49. this.port = port;
  50. try {
  51. selector = Selector.open();
  52. socketChannel = SocketChannel.open();
  53. socketChannel.configureBlocking(false);
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. System.exit(1);
  57. }
  58. }
  59. /* * (non-Javadoc) * * @see java.lang.Runnable#run() */
  60. @Override
  61. public void run() {
  62. try {
  63. doConnect();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. System.exit(1);
  67. }
  68. while (!stop) {
  69. try {
  70. selector.select(1000);
  71. Set<SelectionKey> selectedKeys = selector.selectedKeys();
  72. Iterator<SelectionKey> it = selectedKeys.iterator();
  73. SelectionKey key = null;
  74. while (it.hasNext()) {
  75. key = it.next();
  76. it.remove();
  77. try {
  78. handleInput(key);
  79. } catch (Exception e) {
  80. if (key != null) {
  81. key.cancel();
  82. if (key.channel() != null)
  83. key.channel().close();
  84. }
  85. }
  86. }
  87. } catch (Exception e) {
  88. e.printStackTrace();
  89. System.exit(1);
  90. }
  91. }
  92. // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭,所以不需要重复释放资源
  93. if (selector != null)
  94. try {
  95. selector.close();
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. private void handleInput(SelectionKey key) throws IOException {
  101. if (key.isValid()) {
  102. // 判断是否连接成功
  103. SocketChannel sc = (SocketChannel) key.channel();
  104. if (key.isConnectable()) {
  105. if (sc.finishConnect()) {
  106. sc.register(selector, SelectionKey.OP_READ);
  107. doWrite(sc);
  108. } else
  109. System.exit(1);// 连接失败,进程退出
  110. }
  111. if (key.isReadable()) {
  112. ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  113. int readBytes = sc.read(readBuffer);
  114. if (readBytes > 0) {
  115. readBuffer.flip();
  116. byte[] bytes = new byte[readBuffer.remaining()];
  117. readBuffer.get(bytes);
  118. String body = new String(bytes, StandardCharsets.UTF_8);
  119. System.out.println("Now is : " + body);
  120. this.stop = true;
  121. } else if (readBytes < 0) {
  122. // 对端链路关闭
  123. key.cancel();
  124. sc.close();
  125. } else
  126. ; // 读到0字节,忽略
  127. }
  128. }
  129. }
  130. private void doConnect() throws IOException {
  131. // 如果直接连接成功,则注册到多路复用器上,发送请求消息,读应答
  132. if (socketChannel.connect(new InetSocketAddress(host, port))) {
  133. socketChannel.register(selector, SelectionKey.OP_READ);
  134. doWrite(socketChannel);
  135. } else
  136. socketChannel.register(selector, SelectionKey.OP_CONNECT);
  137. }
  138. private void doWrite(SocketChannel sc) throws IOException {
  139. byte[] req = "QUERY TIME ORDER".getBytes();
  140. ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
  141. writeBuffer.put(req);
  142. writeBuffer.flip();
  143. sc.write(writeBuffer);
  144. if (!writeBuffer.hasRemaining())
  145. System.out.println("Send order 2 server succeed.");
  146. }
  147. }
  148. package main.com.phei.netty.nio;
  149. import java.io.IOException;
  150. import java.net.InetSocketAddress;
  151. import java.nio.ByteBuffer;
  152. import java.nio.channels.SelectionKey;
  153. import java.nio.channels.Selector;
  154. import java.nio.channels.ServerSocketChannel;
  155. import java.nio.channels.SocketChannel;
  156. import java.nio.charset.StandardCharsets;
  157. import java.util.Iterator;
  158. import java.util.Set;
  159. public class MultiplexerTimeServer implements Runnable {
  160. private Selector selector;
  161. private ServerSocketChannel servChannel;
  162. private volatile boolean stop;
  163. /** * 初始化多路复用器、绑定监听端口 * * @param port */
  164. public MultiplexerTimeServer(int port) {
  165. try {
  166. selector = Selector.open();
  167. servChannel = ServerSocketChannel.open();
  168. servChannel.configureBlocking(false);
  169. servChannel.socket().bind(new InetSocketAddress(port), 1024);
  170. servChannel.register(selector, SelectionKey.OP_ACCEPT);
  171. System.out.println("The time server is start in port : " + port);
  172. } catch (IOException e) {
  173. e.printStackTrace();
  174. System.exit(1);
  175. }
  176. }
  177. public void stop() {
  178. this.stop = true;
  179. }
  180. /* * (non-Javadoc) * * @see java.lang.Runnable#run() */
  181. @Override
  182. public void run() {
  183. while (!stop) {
  184. try {
  185. selector.select(1000);
  186. Set<SelectionKey> selectedKeys = selector.selectedKeys();
  187. Iterator<SelectionKey> it = selectedKeys.iterator();
  188. SelectionKey key = null;
  189. while (it.hasNext()) {
  190. key = it.next();
  191. it.remove();
  192. try {
  193. handleInput(key);
  194. } catch (Exception e) {
  195. if (key != null) {
  196. key.cancel();
  197. if (key.channel() != null)
  198. key.channel().close();
  199. }
  200. }
  201. }
  202. } catch (Throwable t) {
  203. t.printStackTrace();
  204. }
  205. }
  206. // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭,所以不需要重复释放资源
  207. if (selector != null) {
  208. try {
  209. selector.close();
  210. } catch (IOException e) {
  211. e.printStackTrace();
  212. }
  213. }
  214. }
  215. private void handleInput(SelectionKey key) throws IOException {
  216. if (key.isValid()) {
  217. // 处理新接入的请求消息
  218. if (key.isAcceptable()) {
  219. // Accept the new connection
  220. ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
  221. SocketChannel sc = ssc.accept();
  222. sc.configureBlocking(false);
  223. // Add the new connection to the selector
  224. sc.register(selector, SelectionKey.OP_READ);
  225. }
  226. if (key.isReadable()) {
  227. // Read the data
  228. SocketChannel sc = (SocketChannel) key.channel();
  229. ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  230. int readBytes = sc.read(readBuffer);
  231. if (readBytes > 0) {
  232. readBuffer.flip();
  233. byte[] bytes = new byte[readBuffer.remaining()];
  234. readBuffer.get(bytes);
  235. String body = new String(bytes, StandardCharsets.UTF_8);
  236. System.out.println("The time server receive order : "
  237. + body);
  238. String currentTime = "QUERY TIME ORDER"
  239. .equalsIgnoreCase(body) ? new java.util.Date(
  240. System.currentTimeMillis()).toString()
  241. : "BAD ORDER";
  242. doWrite(sc, currentTime);
  243. } else if (readBytes < 0) {
  244. // 对端链路关闭
  245. key.cancel();
  246. sc.close();
  247. }
  248. // 读到0字节,忽略
  249. }
  250. }
  251. }
  252. private void doWrite(SocketChannel channel, String response)
  253. throws IOException {
  254. if (response != null && response.trim().length() > 0) {
  255. byte[] bytes = response.getBytes();
  256. ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
  257. writeBuffer.put(bytes);
  258. writeBuffer.flip();
  259. channel.write(writeBuffer);
  260. }
  261. }
  262. }

先启动服务端,再启动客户端,运行结果如下:
在这里插入图片描述
在这里插入图片描述

分析

代码执行完,一脸蒙蔽:
大概可以用下面的流程来理解:
有一个selector 这上面可以注册四个事件:OP_READ ,OP_WRITE ,OP_CONNECT, OP_ACCEPT,并且他本身也在遍历自己的事件,如果有事件注册进来,就进行相应的操作,而他自己先注册一个OP_ACCEPT事件到自身,用来等待连接,这个时候客户端发来一个连接,并且往通道里面输入一个string值,然后服务端遍历到这个OP_CONNECT然后往自身注册一个OP_READ ,然后读取数据。
在这里插入图片描述
所以现在我们再来看网上的一些文章里面讲的NIO的组件,
Selector
一个死循环用来读取注册到其中的key,如果有就进行相应的操作
Channel
负责连接,读取,写入,接受连接的通道,write,read方法用来读写,
ByteBuf
存在channel中,替代之前BIO中的字节数组

最后
确如在BIO最后思考的那样,最有操作都在一个线程里面执行了,达到了多路复用。

几乎所有的中文技术书籍都将 Selector翻译为选择器,但是实际上我认为这样的翻译并不恰当,选择器仅仅是字面上的意思,体现不出 Selector的功能和特点。在前面的章节我们介绍过 Java NIO的实现关键是多路复用I/O技术,多路复用的核心就是通过 Selector来轮询注册在其上的 Channel,当发现某个或者多个 Channel处于就绪状态后,从阻塞状态返回就绪的 Channel的选择键集合,进行I/O操作。由于多路复用器是NIO实现非阻塞1/O的关键,它又是主要通过 Selector实现的,所以本书将 Selector翻译为多路复用器,与其他技术书籍所说的选择器是同一个东西,请大家了解。 ——-Netty权威指南

NIO2.0 (AIO)

  1. package main.com.phei.netty.aio;
  2. /** * @author lilinfeng * @version 1.0 * @date 2014年2月14日 */
  3. public class TimeClient {
  4. /** * @param args */
  5. public static void main(String[] args) {
  6. int port = 8080;
  7. if (args != null && args.length > 0) {
  8. try {
  9. port = Integer.valueOf(args[0]);
  10. } catch (NumberFormatException e) {
  11. // 采用默认值
  12. }
  13. }
  14. new Thread(new AsyncTimeClientHandler("127.0.0.1", port),
  15. "AIO-AsyncTimeClientHandler-001").start();
  16. }
  17. }
  18. package main.com.phei.netty.aio;
  19. import java.io.IOException;
  20. /** * @author lilinfeng * @version 1.0 * @date 2014年2月14日 */
  21. public class TimeServer {
  22. /** * @param args * @throws IOException */
  23. public static void main(String[] args) throws IOException {
  24. int port = 8080;
  25. if (args != null && args.length > 0) {
  26. try {
  27. port = Integer.valueOf(args[0]);
  28. } catch (NumberFormatException e) {
  29. // 采用默认值
  30. }
  31. }
  32. AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(port);
  33. new Thread(timeServer, "AIO-AsyncTimeServerHandler-001").start();
  34. }
  35. }
  36. package main.com.phei.netty.aio;
  37. import java.io.IOException;
  38. import java.net.InetSocketAddress;
  39. import java.nio.channels.AsynchronousServerSocketChannel;
  40. import java.util.concurrent.CountDownLatch;
  41. /** * @author Administrator * @version 1.0 * @date 2014年2月16日 */
  42. public class AsyncTimeServerHandler implements Runnable {
  43. CountDownLatch latch;
  44. AsynchronousServerSocketChannel asynchronousServerSocketChannel;
  45. private int port;
  46. public AsyncTimeServerHandler(int port) {
  47. this.port = port;
  48. try {
  49. asynchronousServerSocketChannel = AsynchronousServerSocketChannel
  50. .open();
  51. asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
  52. System.out.println("The time server is start in port : " + port);
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. /* * (non-Javadoc) * * @see java.lang.Runnable#run() */
  58. @Override
  59. public void run() {
  60. latch = new CountDownLatch(1);
  61. doAccept();
  62. try {
  63. latch.await();
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. public void doAccept() {
  69. asynchronousServerSocketChannel.accept(this,
  70. new AcceptCompletionHandler());
  71. }
  72. }
  73. package main.com.phei.netty.aio;
  74. import java.io.IOException;
  75. import java.io.UnsupportedEncodingException;
  76. import java.net.InetSocketAddress;
  77. import java.nio.ByteBuffer;
  78. import java.nio.channels.AsynchronousSocketChannel;
  79. import java.nio.channels.CompletionHandler;
  80. import java.util.concurrent.CountDownLatch;
  81. /** * @author Administrator * @version 1.0 * @date 2014年2月16日 */
  82. public class AsyncTimeClientHandler implements
  83. CompletionHandler<Void, AsyncTimeClientHandler>, Runnable {
  84. private AsynchronousSocketChannel client;
  85. private String host;
  86. private int port;
  87. private CountDownLatch latch;
  88. public AsyncTimeClientHandler(String host, int port) {
  89. this.host = host;
  90. this.port = port;
  91. try {
  92. client = AsynchronousSocketChannel.open();
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. @Override
  98. public void run() {
  99. latch = new CountDownLatch(1);
  100. client.connect(new InetSocketAddress(host, port), this, this);
  101. try {
  102. latch.await();
  103. } catch (InterruptedException e1) {
  104. e1.printStackTrace();
  105. }
  106. try {
  107. client.close();
  108. } catch (IOException e) {
  109. e.printStackTrace();
  110. }
  111. }
  112. @Override
  113. public void completed(Void result, AsyncTimeClientHandler attachment) {
  114. byte[] req = "QUERY TIME ORDER".getBytes();
  115. ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
  116. writeBuffer.put(req);
  117. writeBuffer.flip();
  118. client.write(writeBuffer, writeBuffer,
  119. new CompletionHandler<Integer, ByteBuffer>() {
  120. @Override
  121. public void completed(Integer result, ByteBuffer buffer) {
  122. if (buffer.hasRemaining()) {
  123. client.write(buffer, buffer, this);
  124. } else {
  125. ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  126. client.read(
  127. readBuffer,
  128. readBuffer,
  129. new CompletionHandler<Integer, ByteBuffer>() {
  130. @Override
  131. public void completed(Integer result,
  132. ByteBuffer buffer) {
  133. buffer.flip();
  134. byte[] bytes = new byte[buffer
  135. .remaining()];
  136. buffer.get(bytes);
  137. String body;
  138. try {
  139. body = new String(bytes,
  140. "UTF-8");
  141. System.out.println("Now is : "
  142. + body);
  143. latch.countDown();
  144. } catch (UnsupportedEncodingException e) {
  145. e.printStackTrace();
  146. }
  147. }
  148. @Override
  149. public void failed(Throwable exc,
  150. ByteBuffer attachment) {
  151. try {
  152. client.close();
  153. latch.countDown();
  154. } catch (IOException e) {
  155. // ingnore on close
  156. }
  157. }
  158. });
  159. }
  160. }
  161. @Override
  162. public void failed(Throwable exc, ByteBuffer attachment) {
  163. try {
  164. client.close();
  165. latch.countDown();
  166. } catch (IOException e) {
  167. // ingnore on close
  168. }
  169. }
  170. });
  171. }
  172. @Override
  173. public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
  174. exc.printStackTrace();
  175. try {
  176. client.close();
  177. latch.countDown();
  178. } catch (IOException e) {
  179. e.printStackTrace();
  180. }
  181. }
  182. }
  183. package main.com.phei.netty.aio;
  184. import java.nio.ByteBuffer;
  185. import java.nio.channels.AsynchronousSocketChannel;
  186. import java.nio.channels.CompletionHandler;
  187. /** * @author lilinfeng * @version 1.0 * @date 2014年2月16日 */
  188. public class AcceptCompletionHandler implements
  189. CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {
  190. @Override
  191. public void completed(AsynchronousSocketChannel result,
  192. AsyncTimeServerHandler attachment) {
  193. attachment.asynchronousServerSocketChannel.accept(attachment, this);
  194. ByteBuffer buffer = ByteBuffer.allocate(1024);
  195. result.read(buffer, buffer, new ReadCompletionHandler(result));
  196. }
  197. @Override
  198. public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
  199. exc.printStackTrace();
  200. attachment.latch.countDown();
  201. }
  202. }
  203. package main.com.phei.netty.aio;
  204. import java.io.IOException;
  205. import java.io.UnsupportedEncodingException;
  206. import java.nio.ByteBuffer;
  207. import java.nio.channels.AsynchronousSocketChannel;
  208. import java.nio.channels.CompletionHandler;
  209. /** * @author lilinfeng * @version 1.0 * @date 2014年2月16日 */
  210. public class ReadCompletionHandler implements
  211. CompletionHandler<Integer, ByteBuffer> {
  212. private AsynchronousSocketChannel channel;
  213. public ReadCompletionHandler(AsynchronousSocketChannel channel) {
  214. if (this.channel == null)
  215. this.channel = channel;
  216. }
  217. @Override
  218. public void completed(Integer result, ByteBuffer attachment) {
  219. attachment.flip();
  220. byte[] body = new byte[attachment.remaining()];
  221. attachment.get(body);
  222. try {
  223. String req = new String(body, "UTF-8");
  224. System.out.println("The time server receive order : " + req);
  225. String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req) ? new java.util.Date(
  226. System.currentTimeMillis()).toString() : "BAD ORDER";
  227. doWrite(currentTime);
  228. } catch (UnsupportedEncodingException e) {
  229. e.printStackTrace();
  230. }
  231. }
  232. private void doWrite(String currentTime) {
  233. if (currentTime != null && currentTime.trim().length() > 0) {
  234. byte[] bytes = (currentTime).getBytes();
  235. ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
  236. writeBuffer.put(bytes);
  237. writeBuffer.flip();
  238. channel.write(writeBuffer, writeBuffer,
  239. new CompletionHandler<Integer, ByteBuffer>() {
  240. @Override
  241. public void completed(Integer result, ByteBuffer buffer) {
  242. // 如果没有发送完成,继续发送
  243. if (buffer.hasRemaining())
  244. channel.write(buffer, buffer, this);
  245. }
  246. @Override
  247. public void failed(Throwable exc, ByteBuffer attachment) {
  248. try {
  249. channel.close();
  250. } catch (IOException e) {
  251. // ingnore on close
  252. }
  253. }
  254. });
  255. }
  256. }
  257. @Override
  258. public void failed(Throwable exc, ByteBuffer attachment) {
  259. try {
  260. this.channel.close();
  261. } catch (IOException e) {
  262. e.printStackTrace();
  263. }
  264. }
  265. }

运行结果如下:
在这里插入图片描述
在这里插入图片描述

最后

下面是几种I/O模型的功能和特性对比:
在这里插入图片描述

Netty之Java I/O演进之路(一)
Netty之NIO入门(二)
Netty之Netty入门应用(三)
Netty之TCP粘包/拆包问题(四)
Netty之编解码开发(五)
Netty之ChannelPipeline(六)
Netty之EventLoop和EventLoopGroup(七)

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty剖析NIO

    什么是NIO? NIO(non blocking IO),是JDK提供的新API。从JDK1.4开始,Java提供了一系列改进的输入/输出的新特性,被统称为 NIO(即