java nio示例

  • 参考 https://crunchify.com/java-nio-non-blocking-io-with-server-client-example-java-nio-bytebuffer-and-channels-selector-java-nio-vs-io/

  • NIOServer.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.ServerSocketChannel;
      import java.nio.channels.SocketChannel;
      import java.util.Iterator;
      import java.util.Set;
    
      public class NIOServer {
    
          public static void main(String[] args) throws IOException {
    
              // Selector: multiplexor of SelectableChannel objects
              Selector selector = Selector.open(); // selector is open here
    
              // ServerSocketChannel: selectable channel for stream-oriented listening sockets
              ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
              InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1111);
    
              // Binds the channel's socket to a local address and configures the socket to listen for connections
              serverSocketChannel.bind(socketAddress);
    
              // Adjusts this channel's blocking mode.
              serverSocketChannel.configureBlocking(false);
    
              int ops = serverSocketChannel.validOps();
              serverSocketChannel.register(selector, ops, null);
    
              // Infinite loop..
              // Keep server running
              while (true) {
    
                  log("i'm a server and i'm waiting for new connection and buffer select...");
    
                  // Selects a set of keys whose corresponding channels are ready for I/O operations
                  selector.select();
    
                  // token representing the registration of a SelectableChannel with a Selector
                  Set<SelectionKey> selectionKeys = selector.selectedKeys();
                  Iterator<SelectionKey> iterator = selectionKeys.iterator();
    
                  while (iterator.hasNext()) {
    
                      SelectionKey currentKey = iterator.next();
    
                      // Tests whether this key's channel is ready to accept a new socket connection
                      if (currentKey.isAcceptable()) {
    
                          SocketChannel socketChannel = serverSocketChannel.accept();
    
                          // Adjusts this channel's blocking mode to false
                          socketChannel.configureBlocking(false);
    
                          // Operation-set bit for read operations
                          socketChannel.register(selector, SelectionKey.OP_READ);
    
                          log("Connection Accepted: " + socketChannel.getLocalAddress() + "\n");
    
                          // Tests whether this key's channel is ready for reading
                      } else if (currentKey.isReadable()) {
    
                          SocketChannel socketChannel = (SocketChannel) currentKey.channel();
                      
                          ByteBuffer buffer = ByteBuffer.allocate(256);
                          socketChannel.read(buffer);
                  
                          String result = new String(buffer.array()).trim();
    
                          log("Message received: " + result);
    
                          if (result.equals("Crunchify")) {
    
                              socketChannel.close();
                              log("\nIt's time to close connection as we got last company name 'Crunchify'");
                              log("\nServer will keep running. Try running client again to establish new connection");
                          }
                      }
    
                      iterator.remove();
                  }
              }
          }
    
          private static void log(String str) {
              System.out.println(str);
          }
      }
    
  • NIOClient

      import java.io.IOException;
      import java.net.InetSocketAddress;
      import java.nio.ByteBuffer;
      import java.nio.channels.SocketChannel;
      import java.util.ArrayList;
    
      public class NIOClient {
    
          public static void main(String[] args) throws IOException, InterruptedException {
    
              InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1111);
              SocketChannel socketChannel = SocketChannel.open(socketAddress);
    
              log("Connecting to Server on port 1111...");
    
              ArrayList<String> companyDetails = new ArrayList<>();
    
              // create a ArrayList with companyName list
              companyDetails.add("Facebook");
              companyDetails.add("Twitter");
              companyDetails.add("IBM");
              companyDetails.add("Google");
              companyDetails.add("Crunchify");
    
              for (String companyName : companyDetails) {
    
                  byte[] message = companyName.getBytes();
                  ByteBuffer buffer = ByteBuffer.wrap(message);
                  socketChannel.write(buffer);
    
                  log("sending: " + companyName);
                  buffer.clear();
    
                  // wait for 2 seconds before sending next message
                  Thread.sleep(2000);
              }
    
              socketChannel.close();
          }
    
          private static void log(String str) {
              System.out.println(str);
          }
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值