文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java NIO代码怎么写

2023-06-17 11:59

关注

这篇文章主要讲解了“Java NIO代码怎么写”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java NIO代码怎么写”吧!

Java代码:

import java.io.IOException;  import java.net.InetSocketAddress;  import java.net.ServerSocket;  import java.nio.ByteBuffer;  import java.nio.channels.SelectionKey;  import java.nio.channels.Selector;  import java.nio.channels.ServerSocketChannel;  import java.nio.channels.SocketChannel;  import java.util.Iterator;  import java.util.Set;   public class NIOServer {                 private  int flag = 0;           private  int BLOCK = 4096;           private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);           private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);      private  Selector selector;       public NIOServer(int port) throws IOException {          // 打开服务器套接字通道          ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();          // 服务器配置为非阻塞          serverSocketChannel.configureBlocking(false);          // 检索与此通道关联的服务器套接字          ServerSocket serverSocket = serverSocketChannel.socket();          // 进行服务的绑定          serverSocket.bind(new InetSocketAddress(port));          // 通过open()方法找到Selector          selector = Selector.open();          // 注册到selector,等待连接          serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);          System.out.println("Server Start----8888:");      }        // 监听      private void listen() throws IOException {          while (true) {              // 选择一组键,并且相应的通道已经打开              selector.select();              // 返回此选择器的已选择键集。              Set<SelectionKey> selectionKeys = selector.selectedKeys();              Iterator<SelectionKey> iterator = selectionKeys.iterator();              while (iterator.hasNext()) {                          SelectionKey selectionKey = iterator.next();                  iterator.remove();                  handleKey(selectionKey);              }          }      }       // 处理请求      private void handleKey(SelectionKey selectionKey) throws IOException {          // 接受请求          ServerSocketChannel server = null;          SocketChannel client = null;          String receiveText;          String sendText;          int count=0;          // 测试此键的通道是否已准备好接受新的套接字连接。          if (selectionKey.isAcceptable()) {              // 返回为之创建此键的通道。              server = (ServerSocketChannel) selectionKey.channel();              // 接受到此通道套接字的连接。              // 此方法返回的套接字通道(如果有)将处于阻塞模式。              client = server.accept();              // 配置为非阻塞              client.configureBlocking(false);              // 注册到selector,等待连接              client.register(selector, SelectionKey.OP_READ);          } else if (selectionKey.isReadable()) {              // 返回为之创建此键的通道。              client = (SocketChannel) selectionKey.channel();              //将缓冲区清空以备下次读取              receivebuffer.clear();              //读取服务器发送来的数据到缓冲区中              count = client.read(receivebuffer);               if (count > 0) {                  receiveText = new String( receivebuffer.array(),0,count);                  System.out.println("服务器端接受客户端数据--:"+receiveText);                  client.register(selector, SelectionKey.OP_WRITE);              }          } else if (selectionKey.isWritable()) {              //将缓冲区清空以备下次写入              sendbuffer.clear();              // 返回为之创建此键的通道。              client = (SocketChannel) selectionKey.channel();              sendText="message from server--" + flag++;              //向缓冲区中输入数据              sendbuffer.put(sendText.getBytes());               //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位              sendbuffer.flip();              //输出到通道              client.write(sendbuffer);              System.out.println("服务器端向客户端发送数据--:"+sendText);              client.register(selector, SelectionKey.OP_READ);          }      }            public static void main(String[] args) throws IOException {          // TODO Auto-generated method stub          int port = 8888;          NIOServer server = new NIOServer(port);          server.listen();      }  }

Java代码:

import java.io.IOException;  import java.net.InetSocketAddress;  import java.nio.ByteBuffer;  import java.nio.channels.SelectionKey;  import java.nio.channels.Selector;  import java.nio.channels.SocketChannel;  import java.util.Iterator;  import java.util.Set;   public class NIOClient {            private static int flag = 0;           private static int BLOCK = 4096;           private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);           private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);           private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(              "localhost", 1111);       public static void main(String[] args) throws IOException {          // TODO Auto-generated method stub          // 打开socket通道          SocketChannel socketChannel = SocketChannel.open();          // 设置为非阻塞方式          socketChannel.configureBlocking(false);          // 打开选择器          Selector selector = Selector.open();          // 注册连接服务端socket动作          socketChannel.register(selector, SelectionKey.OP_CONNECT);          // 连接          socketChannel.connect(SERVER_ADDRESS);          // 分配缓冲区大小内存                    Set<SelectionKey> selectionKeys;          Iterator<SelectionKey> iterator;          SelectionKey selectionKey;          SocketChannel client;          String receiveText;          String sendText;          int count=0;           while (true) {              //选择一组键,其相应的通道已为 I/O 操作准备就绪。              //此方法执行处于阻塞模式的选择操作。              selector.select();              //返回此选择器的已选择键集。              selectionKeys = selector.selectedKeys();              //System.out.println(selectionKeys.size());              iterator = selectionKeys.iterator();              while (iterator.hasNext()) {                  selectionKey = iterator.next();                  if (selectionKey.isConnectable()) {                      System.out.println("client connect");                      client = (SocketChannel) selectionKey.channel();                      // 判断此通道上是否正在进行连接操作。                      // 完成套接字通道的连接过程。                      if (client.isConnectionPending()) {                          client.finishConnect();                          System.out.println("完成连接!");                          sendbuffer.clear();                          sendbuffer.put("Hello,Server".getBytes());                          sendbuffer.flip();                          client.write(sendbuffer);                      }                      client.register(selector, SelectionKey.OP_READ);                  } else if (selectionKey.isReadable()) {                      client = (SocketChannel) selectionKey.channel();                      //将缓冲区清空以备下次读取                      receivebuffer.clear();                      //读取服务器发送来的数据到缓冲区中                      count=client.read(receivebuffer);                      if(count>0){                          receiveText = new String( receivebuffer.array(),0,count);                          System.out.println("客户端接受服务器端数据--:"+receiveText);                          client.register(selector, SelectionKey.OP_WRITE);                      }                   } else if (selectionKey.isWritable()) {                      sendbuffer.clear();                      client = (SocketChannel) selectionKey.channel();                      sendText = "message from client--" + (flag++);                      sendbuffer.put(sendText.getBytes());                       //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位                      sendbuffer.flip();                      client.write(sendbuffer);                      System.out.println("客户端向服务器端发送数据--:"+sendText);                      client.register(selector, SelectionKey.OP_READ);                  }              }              selectionKeys.clear();          }      }  }

感谢各位的阅读,以上就是“Java NIO代码怎么写”的内容了,经过本文的学习后,相信大家对Java NIO代码怎么写这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯