JavaSE:NIO - accept阻塞问题(设置非阻塞)

<1>服务器端代码

import  java.io.IOException;

import  java.net.InetSocketAddress;

import  java.nio.ByteBuffer;

import  java.nio.channels.ServerSocketChannel;

import  java.nio.channels.SocketChannel;



public class Demo服务端非阻塞 {

  // 阻塞的

  main() throws IOException, InterruptedException{

    
    // 创建服务器端对象
    ServerSocketChannel ssc = ServerSocketChannel.open();


    // 绑定端口号
    ssc.bind(new InetSocketAddress(9000));


    // **设置非阻塞**
    ssc.configureBlocking(false);


    while(true){

      // 连接客户端
          // 如果连接成功就是sc对象,如果没有连接,就是 sc = null

      SocketChannel sc = ssc.accept();


      // 判断
      // <1> 有客户连接到了服务器
      if (sc != null
) {         // 创建缓冲数组         ByteBuffer buffer = ByteBuffer.allocate(1024);         // 读取数据         int len = sc.read(buffer);         // 打印         System.out.println(new String(buffer.array(),0,len));         // 结束循环         break;       } else {         // <2> 没有客户连接服务器         // 在这里可以写别的业务代码         System.out.println("去忙点别的事儿...");         Thread.sleep(3000);       }     }   } }

 

<2>运行效果:

 

posted @ 2021-07-01 16:13  Jasper2003  阅读(155)  评论(0编辑  收藏  举报