集册 Java实例教程 带有ServerSocketChannel的非阻塞接受

带有ServerSocketChannel的非阻塞接受

欢马劈雪     最近更新时间:2020-01-02 10:19:05

469
使用ServerSocketChannel的非阻塞accept()

import java.net.InetSocketAddress;/*来自 时 代 J     a    v  a - nowjava.com*/

import java.nio.ByteBuffer;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;


public class Main {


  public static void main(String[] argv) throws Exception {

    int port = 1234; // default

    ByteBuffer buffer = ByteBuffer.wrap("this is a test".getBytes());

    ServerSocketChannel ssc = ServerSocketChannel.open();

    ssc.socket().bind(new InetSocketAddress(port));

    ssc.configureBlocking(false);

    while (true) {

      System.out.println("Waiting for connections");

      SocketChannel sc = ssc.accept();

      if (sc == null) {

         Thread.sleep(2000);

      } else {

        System.out.println(
展开阅读全文