马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

Java中NIO及基础实现

[复制链接]
查看2317 | 回复1 | 2019-10-17 09:45:07 | 显示全部楼层 |阅读模式

NIO:同步非壅闭IO

来源:BIO是同步壅闭IO利用,当线程在处理使命时,另一方会壅闭着等待该线程的执行完毕,为了进步效率,,JDK1.4后,引入NIO来提升数据的通讯性能

NIO中接纳Reactor计划模式,注册的汇集点为Selector,NIO有三个紧张构成部门:Channel(通道)、Buffer(缓冲区)、Selector(选择器)

Reactor计划模式:Reactor模式是一种被动事件处理模式,即当某个特定事件发生时触发事件,可参考,https://blog.csdn.net/feimataxue/article/details/7642638,https://www.cnblogs.com/bitkevin/p/5724410.html

NIO接纳了轮询的方式来观察事件是否执行完毕,如:A让B打印某个文件,BIO会不停等待着B返回,期间自己不做其他事变,而NIO则会不停的询问B是否完成,未完成则处理自己的时,直至B完成

Channel(通道):Channel是一个对象,可以通过它读取和写入数据

Selector(对象选择器): Selector是一个对象,它可以注册到很多个Channel上,监听各个Channel上发生的事件,并且可以或许根据事件情况决定Channel读写

代码实现:(此实现参考网络上可用的例子)

NIO客户端实现:

  1. package com.learn.nio.client;
  2. import com.study.info.HostInfo;
  3. import com.study.util.InputUtil;
  4. import java.net.InetSocketAddress;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.SocketChannel;
  7. public class NIOEchoClient {
  8. public static void main(String[] args) throws Exception{
  9. SocketChannel clientChannel = SocketChannel.open();
  10. clientChannel.connect(new InetSocketAddress(HostInfo.HOST_NAME,HostInfo.PORT));
  11. ByteBuffer buffer = ByteBuffer.allocate(50);
  12. boolean flag = true;
  13. while (flag){
  14. buffer.clear();
  15. String input = InputUtil.getString("请输入待发送的信息:").trim();
  16. buffer.put(input.getBytes()); //将数据存入缓冲区
  17. buffer.flip(); // 重置缓冲区
  18. clientChannel.write(buffer); //发送数据
  19. buffer.clear();
  20. int read = clientChannel.read(buffer);
  21. buffer.flip();
  22. System.err.print(new String(buffer.array(), 0, read));
  23. if("byebye".equalsIgnoreCase(input)){
  24. flag = false;
  25. }
  26. }
  27. clientChannel.close();
  28. }
  29. }
复制代码

NIO服务端实现:

  1. package com.learn.nio.server;
  2. import com.study.info.HostInfo;
  3. import java.net.InetSocketAddress;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.SelectionKey;
  6. import java.nio.channels.Selector;
  7. import java.nio.channels.ServerSocketChannel;
  8. import java.nio.channels.SocketChannel;
  9. import java.util.Iterator;
  10. import java.util.Set;
  11. import java.util.concurrent.ExecutorService;
  12. import java.util.concurrent.Executors;
  13. public class NIOEchoServer {
  14. private static class EchoClientHandle implements Runnable {
  15. //客户端
  16. private SocketChannel clientChannel;
  17. // 循环竣事标记
  18. private boolean flag = true;
  19. public EchoClientHandle(SocketChannel clientChannel){
  20. this.clientChannel = clientChannel;
  21. }
  22. @Override
  23. public void run() {
  24. ByteBuffer byteBuffer = ByteBuffer.allocate(50);
  25. try {
  26. while (this.flag){
  27. byteBuffer.clear();
  28. int read = this.clientChannel.read(byteBuffer);
  29. String msg = new String(byteBuffer.array(), 0, read).trim();
  30. String outMsg = "【Echo】" + msg + "\n"; // 回应信息
  31. if("byebve".equals(msg)){
  32. outMsg = "会话竣事,下次再见!";
  33. this.flag = false;
  34. }
  35. byteBuffer.clear();
  36. byteBuffer.put(outMsg.getBytes()); //回传信息放入缓冲区
  37. byteBuffer.flip();
  38. this.clientChannel.write(byteBuffer);// 回传信息
  39. }
  40. }catch (Exception e){
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. public static void main(String[] args) throws Exception{
  46. // 为了性能问题及相应时间,设置固定大小的线程池
  47. ExecutorService executorService = Executors.newFixedThreadPool(10);
  48. // NIO基于Channel控制,所以有Selector管理全部的Channel
  49. ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
  50. // 设置为非壅闭模式
  51. serverSocketChannel.configureBlocking(false);
  52. // 设置监听端口
  53. serverSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
  54. // 设置Selector管理全部Channel
  55. Selector selector = Selector.open();
  56. // 注册并设置毗连时处理
  57. serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  58. System.out.println("服务启动乐成,监听端口为:" + HostInfo.PORT);
  59. // NIO使用轮询,当有请求毗连时,则启动一个线程
  60. int keySelect = 0;
  61. while ((keySelect = selector.select()) > 0){
  62. Set<SelectionKey> selectionKeys = selector.selectedKeys();
  63. Iterator<SelectionKey> iterator = selectionKeys.iterator();
  64. while (iterator.hasNext()){
  65. SelectionKey next = iterator.next();
  66. if(next.isAcceptable()){ // 假如是毗连的
  67. SocketChannel accept = serverSocketChannel.accept();
  68. if(accept != null){
  69. executorService.submit(new EchoClientHandle(accept));
  70. }
  71. iterator.remove();
  72. }
  73. }
  74. }
  75. executorService.shutdown();
  76. serverSocketChannel.close();
  77. }
  78. }
复制代码

工具类:

  1. package com.study.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. public class InputUtil {
  6. private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));
  7. private InputUtil(){
  8. }
  9. public static String getString(String prompt){
  10. boolean flag = true; //数据接受标记
  11. String str = null;
  12. while (flag){
  13. System.out.println(prompt);
  14. try {
  15. str = KEYBOARD_INPUT.readLine(); // 读取一行数据
  16. if(str == null || "".equals(str)){
  17. System.out.println("数据输入错误,不允许为空!");
  18. }else {
  19. flag = false;
  20. }
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. return str;
  26. }
  27. }
复制代码
  1. package com.study.info;
  2. public calss HostInfo {
  3. public static final String HOST_NAME = "localhost";
  4. public static final int PORT = 9999;
  5. }
复制代码

NIO结构参考文章: https://www.cnblogs.com/sxkgeek/p/9488703.html#_label2







来源:https://www.cnblogs.com/shlearn/p/11689427.html
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则