Java Code Examples for java.nio.channels.ServerSocketChannel#socket()

The following examples show how to use java.nio.channels.ServerSocketChannel#socket() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NioServer.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
private void init() {

        ServerSocketChannel socketChannel = processor.javaChannel();

        ServerSocket javaSocket = socketChannel.socket();

        try {
            if (serverConfig.getReceiveBufferSize() != null) {
                javaSocket.setReceiveBufferSize(serverConfig.getReceiveBufferSize());
            }
            if (serverConfig.getReuseAddress() != null) {
                javaSocket.setReuseAddress(serverConfig.getReuseAddress());
            }
        } catch (SocketException e) {
            throw new NioException("config channel error:" + e.getMessage(), e);
        }
    }
 
Example 2
Source File: TestIPv6NIOServerSocketChannel.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
 * there. Then binds the obtained socket.
 * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
 * IPv6 address. Works on Oracle JDK 1.7.
 */
private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
  while (true) {
    int port = HBaseTestingUtility.randomFreePort();
    InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
    ServerSocketChannel channel = null;
    ServerSocket serverSocket = null;
    try {
      channel = ServerSocketChannel.open();
      serverSocket = channel.socket();
      serverSocket.bind(addr); // This does not work
      break;
    } catch (BindException ex) {
      //continue
    } finally {
      if (serverSocket != null) {
        serverSocket.close();
      }
      if (channel != null) {
        channel.close();
      }
    }
  }
}
 
Example 3
Source File: NioServer.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
private void init() {

        ServerSocketChannel socketChannel = processor.javaChannel();

        ServerSocket javaSocket = socketChannel.socket();

        try {
            if (serverConfig.getReceiveBufferSize() != null) {
                javaSocket.setReceiveBufferSize(serverConfig.getReceiveBufferSize());
            }
            if (serverConfig.getReuseAddress() != null) {
                javaSocket.setReuseAddress(serverConfig.getReuseAddress());
            }
        } catch (SocketException e) {
            throw new NioException("config channel error:" + e.getMessage(), e);
        }
    }
 
Example 4
Source File: NIOServer.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
void startServer() throws IOException {
    // 准备好一个选择器, 监控是否有链接 (OP_ACCEPT)
    SelectorLoop connectionBell = new SelectorLoop();

    // 准备好一个选择器, 监控是否有read事件 (OP_READ)
    readBell = new SelectorLoop();

    // 开启一个server channel来监听
    ServerSocketChannel ssc = ServerSocketChannel.open();
    // 开启非阻塞模式
    ssc.configureBlocking(false);

    ServerSocket socket = ssc.socket();
    socket.bind(new InetSocketAddress("localhost", SOCKET_PORT));

    // 给选择器规定好要监听报告的事件, 这个选择器只监听新连接事件
    ssc.register(connectionBell.getSelector(), SelectionKey.OP_ACCEPT);
    new Thread(connectionBell).start();
}
 
Example 5
Source File: NIOConnector.java    From ServletContainer with GNU General Public License v3.0 5 votes vote down vote up
public NIOConnector init() {
    try {
        this.selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket serverSocket = serverSocketChannel.socket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(80);
        serverSocket.bind(inetSocketAddress);
        serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
    }catch(IOException e){
        e.printStackTrace();
    }
    return this;
}
 
Example 6
Source File: NioTcpAcceptor.java    From craft-atom with MIT License 5 votes vote down vote up
@Override
protected void bindByProtocol(SocketAddress address) throws IOException {
	ServerSocketChannel ssc = ServerSocketChannel.open();
	ssc.configureBlocking(false);
	ServerSocket ss = ssc.socket();
	ss.setReuseAddress(config.isReuseAddress());
	ss.bind(address, config.getBacklog());
	ssc.register(selector, SelectionKey.OP_ACCEPT);
	boundmap.put(address, ssc);
}
 
Example 7
Source File: ServerSocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests ServerSocketChannel#socket().getSoTimeout()
 */
public void test_accept_SOTIMEOUT() throws IOException {
    // Regression test for Harmony-707
    // The timeout actually used may be different from the one set due to
    // rounding by the Linux Kernel (see sock_set_timeout() in net/core/sock.c).
    // getSoTimeout() can return a different value from the one set with
    // setSoTimeout(). Consequently we do not check for equality with what was
    // set.

    ServerSocketChannel sc = ServerSocketChannel.open();
    try {
        sc.socket().bind(null);

        // Non blocking mode, accept() will return NULL since there are no pending connections.
        sc.configureBlocking(false);

        ServerSocket ss = sc.socket();

        int defaultTimeout = ss.getSoTimeout();
        assertEquals(0, defaultTimeout);
        // The timeout value is unimportant, providing it is large enough to be accepted
        // by the Kernel as distinct from the default.
        final int SO_TIMEOUT = 200;
        ss.setSoTimeout(SO_TIMEOUT);
        int nonDefaultTimeout = ss.getSoTimeout();
        assertTrue(nonDefaultTimeout != defaultTimeout);

        SocketChannel client = sc.accept();
        assertNull(client);
        // Confirm the timeout was unchanged.
        assertEquals(nonDefaultTimeout, ss.getSoTimeout());
    } finally {
        sc.close();
    }
}
 
Example 8
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for Harmony-1947.
 */
public void test_finishConnect() throws Exception {
    SocketAddress address = new InetSocketAddress("localhost", 0);

    ServerSocketChannel theServerChannel = ServerSocketChannel.open();
    ServerSocket serversocket = theServerChannel.socket();
    serversocket.setReuseAddress(true);
    // Bind the socket
    theServerChannel.socket().bind(address);

    boolean doneNonBlockingConnect = false;
    // Loop so that we make sure we're definitely testing finishConnect()
    while (!doneNonBlockingConnect) {
        channel1 = SocketChannel.open();

        // Set the SocketChannel to non-blocking so that connect(..) does
        // not block
        channel1.configureBlocking(false);
        boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
        if (!connected) {
            // Now set the SocketChannel back to blocking so that
            // finishConnect() blocks.
            channel1.configureBlocking(true);
            doneNonBlockingConnect = channel1.finishConnect();
        }
        if (doneNonBlockingConnect) {
            tryFinish();
        }
        channel1.close();
    }
    if (!serversocket.isClosed()) {
        serversocket.close();
    }
}
 
Example 9
Source File: GemFireMemcachedServer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void startMemcachedServer() throws IOException, InterruptedException {
  ServerSocketChannel channel = ServerSocketChannel.open();
  final ServerSocket serverSocket = channel.socket();
  serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), serverPort));
  final CountDownLatch latch = new CountDownLatch(1);
  acceptor = new Thread(new Runnable() {
    public void run() {
      for (;;) {
        Socket s = null;
        try {
          latch.countDown();
          s = serverSocket.accept();
          handleNewClient(s);
        } catch (ClosedByInterruptException e) {
          try {
            serverSocket.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
          break;
        } catch (IOException e) {
          e.printStackTrace();
          break;
        }
      }
    }
  }, "AcceptorThread");
  acceptor.setDaemon(true);
  acceptor.start();
  latch.await();
  logger.config("GemFireMemcachedServer server started on host:"+SocketCreator.getLocalHost()+" port: "+this.serverPort);
}
 
Example 10
Source File: GemFireMemcachedServer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void startMemcachedServer() throws IOException, InterruptedException {
  ServerSocketChannel channel = ServerSocketChannel.open();
  final ServerSocket serverSocket = channel.socket();
  serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), serverPort));
  final CountDownLatch latch = new CountDownLatch(1);
  acceptor = new Thread(new Runnable() {
    public void run() {
      for (;;) {
        Socket s = null;
        try {
          latch.countDown();
          s = serverSocket.accept();
          handleNewClient(s);
        } catch (ClosedByInterruptException e) {
          try {
            serverSocket.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
          break;
        } catch (IOException e) {
          e.printStackTrace();
          break;
        }
      }
    }
  }, "AcceptorThread");
  acceptor.setDaemon(true);
  acceptor.start();
  latch.await();
  logger.config("GemFireMemcachedServer server started on host:"+SocketCreator.getLocalHost()+" port: "+this.serverPort);
}
 
Example 11
Source File: NioSocketAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
    // Creates the listening ServerSocket
    ServerSocketChannel channel = ServerSocketChannel.open();

    boolean success = false;

    try {
        // This is a non blocking socket channel
        channel.configureBlocking(false);

        // Configure the server socket,
        ServerSocket socket = channel.socket();

        // Set the reuseAddress flag accordingly with the setting
        socket.setReuseAddress(isReuseAddress());

        // and bind.
        socket.bind(localAddress, getBacklog());

        // Register the channel within the selector for ACCEPT event
        channel.register(selector, SelectionKey.OP_ACCEPT);
        success = true;
    } finally {
        if (!success) {
            close(channel);
        }
    }
    return channel;
}
 
Example 12
Source File: SelectorThread.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException
{
    ServerSocketChannel selectable = ServerSocketChannel.open();
    selectable.configureBlocking(false);

    ServerSocket ss = selectable.socket();
    
    if (address == null)
        ss.bind(new InetSocketAddress(tcpPort));
    else
        ss.bind(new InetSocketAddress(address, tcpPort));
    
    selectable.register(_selector, SelectionKey.OP_ACCEPT);
}
 
Example 13
Source File: NIOServer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 1、创建选择器
    Selector selector = Selector.open();
    // 2、将通道注册到选择器上
    ServerSocketChannel ssChannel = ServerSocketChannel.open();
    // 设置非阻塞
    ssChannel.configureBlocking(false);
    ssChannel.register(selector, SelectionKey.OP_ACCEPT);
    // 3、监听事件
    ServerSocket serverSocket = ssChannel.socket();
    serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));

    while (true) {
        selector.select();
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keys.iterator();
        // 5、事件循环
        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            // 4、获取到达的事件
            if (key.isAcceptable()) {
                ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
                // 服务器会为每个新连接创建一个 SocketChannel
                SocketChannel socketChannel = ssChannel1.accept();
                socketChannel.configureBlocking(false);
                // 这个新连接主要用于从客户端读取数据
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                SocketChannel sChannel = (SocketChannel) key.channel();
                System.out.println(readDataFromSocketChannel(sChannel));
                sChannel.close();
            }
            keyIterator.remove();
        }

    }

}
 
Example 14
Source File: SocketCreator.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Creates or bind server socket to a random port selected
 * from tcp-port-range which is same as membership-port-range.
 * @param ba
 * @param backlog
 * @param isBindAddress
 * @param logger
 * @param tcpBufferSize
 * @return Returns the new server socket.
 * @throws IOException
 */
public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog,
    boolean isBindAddress, boolean useNIO, GFLogWriter logger,
    int tcpBufferSize, int[] tcpPortRange) throws IOException {
  
  ServerSocket socket = null;
  int localPort = 0;
  int startingPort = 0;
  
  // Get a random port from range.
  Random rand = new SecureRandom();
  int portLimit = tcpPortRange[1];
  int randPort = tcpPortRange[0] + rand.nextInt(tcpPortRange[1] - tcpPortRange[0] + 1);

  startingPort = randPort;
  localPort = startingPort;

  while (true) {
    if (localPort > portLimit) {
      if (startingPort != 0) {
        localPort = tcpPortRange[0];
        portLimit = startingPort - 1;
        startingPort = 0;
      } else {
        throw new SystemConnectException(
            LocalizedStrings.TCPConduit_UNABLE_TO_FIND_FREE_PORT.toLocalizedString());
      }
    }
    try {
      if (useNIO) {
        ServerSocketChannel channl = ServerSocketChannel.open();
        socket = channl.socket();

        InetSocketAddress addr = new InetSocketAddress(isBindAddress ? ba : null, localPort);
        socket.bind(addr, backlog);
      } else {
        socket = SocketCreator.getDefaultInstance().createServerSocket(localPort, backlog, isBindAddress? ba : null, logger, tcpBufferSize);
      }
      break;
    } catch (java.net.SocketException ex) {
      if (useNIO || SocketCreator.treatAsBindException(ex)) {
        localPort++;
      } else {
        throw ex;
      }
    }
  }
  return socket;
}
 
Example 15
Source File: SocketCreator.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Creates or bind server socket to a random port selected
 * from tcp-port-range which is same as membership-port-range.
 * @param ba
 * @param backlog
 * @param isBindAddress
 * @param logger
 * @param tcpBufferSize
 * @return Returns the new server socket.
 * @throws IOException
 */
public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog,
    boolean isBindAddress, boolean useNIO, GFLogWriter logger,
    int tcpBufferSize, int[] tcpPortRange) throws IOException {
  
  ServerSocket socket = null;
  int localPort = 0;
  int startingPort = 0;
  
  // Get a random port from range.
  Random rand = new SecureRandom();
  int portLimit = tcpPortRange[1];
  int randPort = tcpPortRange[0] + rand.nextInt(tcpPortRange[1] - tcpPortRange[0] + 1);

  startingPort = randPort;
  localPort = startingPort;

  while (true) {
    if (localPort > portLimit) {
      if (startingPort != 0) {
        localPort = tcpPortRange[0];
        portLimit = startingPort - 1;
        startingPort = 0;
      } else {
        throw new SystemConnectException(
            LocalizedStrings.TCPConduit_UNABLE_TO_FIND_FREE_PORT.toLocalizedString());
      }
    }
    try {
      if (useNIO) {
        ServerSocketChannel channl = ServerSocketChannel.open();
        socket = channl.socket();

        InetSocketAddress addr = new InetSocketAddress(isBindAddress ? ba : null, localPort);
        socket.bind(addr, backlog);
      } else {
        socket = SocketCreator.getDefaultInstance().createServerSocket(localPort, backlog, isBindAddress? ba : null, logger, tcpBufferSize);
      }
      break;
    } catch (java.net.SocketException ex) {
      if (useNIO || SocketCreator.treatAsBindException(ex)) {
        localPort++;
      } else {
        throw ex;
      }
    }
  }
  return socket;
}
 
Example 16
Source File: Reactor.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务。
 */
public void start() {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(_port));
        _isRun = true;
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +_port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(selector, serverChannel));
        
        while (_isRun) {
            int selectNum = selector.select(_selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                     Acceptor acceptor = (Acceptor) selectionKey.attachment();
                     acceptor.accept();
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    Reader reader = (Reader) selectionKey.attachment();
                    reader.read();
                }
                
                // 移除已经处理过的Key
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}
 
Example 17
Source File: ShellLaunchManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Registers the connection and initiates the listening socket.
 * @param project the project which is being run / debugged
 * @param debugger if true, the connection will pair with a debugger session.
 */
public ShellAgent openForProject(Project p, boolean debugger) throws IOException {
    ServerSocket ss;
    
    String encodedKey;
    boolean shouldInit = false;
    
    synchronized (this) {
        shouldInit = usedKeys.isEmpty();
        do {
            BigInteger key = BigInteger.probablePrime(64, keyGenerator);
            encodedKey = key.toString(Character.MAX_RADIX);
        } while (!usedKeys.add(encodedKey));
    }
    
    if (shouldInit) {
        init();
    }
    
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    SocketAddress local = new InetSocketAddress(
        // PENDING: choose something better for remote debugging!
        InetAddress.getLoopbackAddress(),
        0);
    ssc.bind(local);
    ssc.accept();
    ss = ssc.socket();
    LOG.log(Level.FINE, "Creating new server socket {0} for project: {1}", new Object[] {
        ss, p
    });
    ShellAgent agent = new ShellAgent(this, p, ss, encodedKey, debugger);
    synchronized (this) {
        registeredAgents.put(encodedKey, agent);
    }
    synchronized (requests) {
        servers.wakeup();
        requests.add(agent);
        
    }
    return agent;
}
 
Example 18
Source File: SocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void checkSocketLocalAndRemoteAddresses(boolean setOptions) throws Exception {
    InetAddress host = InetAddress.getLocalHost();

    // Open a local server port.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    InetSocketAddress listenAddr = new InetSocketAddress(host, 0);
    try {
      ssc.socket().bind(listenAddr, 0);
    } catch (BindException e) {
      // Continuous build environment doesn't support localhost sockets.
      return;
    }
    ServerSocket ss = ssc.socket();

    // Open a socket to the local port.
    SocketChannel out = SocketChannel.open();
    out.configureBlocking(false);
    if (setOptions) {
        out.socket().setTcpNoDelay(false);
    }
    InetSocketAddress addr = new InetSocketAddress(host, ssc.socket().getLocalPort());
    out.connect(addr);
    while (!out.finishConnect()) {
        Thread.sleep(1);
    }

    SocketChannel in = ssc.accept();
    if (setOptions) {
        in.socket().setTcpNoDelay(false);
    }

    InetSocketAddress listenAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
    InetSocketAddress outRemoteAddress = (InetSocketAddress) out.socket().getRemoteSocketAddress();
    InetSocketAddress outLocalAddress = (InetSocketAddress) out.socket().getLocalSocketAddress();
    InetSocketAddress inLocalAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
    InetSocketAddress inRemoteAddress = (InetSocketAddress) in.socket().getRemoteSocketAddress();
    //System.err.println("listenAddress: " + listenAddr);
    //System.err.println("inLocalAddress: " + inLocalAddress);
    //System.err.println("inRemoteAddress: " + inRemoteAddress);
    //System.err.println("outLocalAddress: " + outLocalAddress);
    //System.err.println("outRemoteAddress: " + outRemoteAddress);

    assertEquals(outRemoteAddress.getPort(), ss.getLocalPort());
    assertEquals(inLocalAddress.getPort(), ss.getLocalPort());
    assertEquals(inRemoteAddress.getPort(), outLocalAddress.getPort());

    assertEquals(inLocalAddress.getAddress(), ss.getInetAddress());
    assertEquals(inRemoteAddress.getAddress(), ss.getInetAddress());
    assertEquals(outLocalAddress.getAddress(), ss.getInetAddress());
    assertEquals(outRemoteAddress.getAddress(), ss.getInetAddress());

    assertFalse(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertTrue(in.isConnected());
    assertTrue(in.socket().isConnected());
    assertTrue(out.socket().isConnected());
    assertTrue(out.isConnected());

    in.close();
    out.close();
    ssc.close();

    assertTrue(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertFalse(in.isConnected());
    assertFalse(in.socket().isConnected());
    assertFalse(out.socket().isConnected());
    assertFalse(out.isConnected());

    assertNull(in.socket().getRemoteSocketAddress());
    assertNull(out.socket().getRemoteSocketAddress());

    // As per docs and RI - server socket local address methods continue to return the bind()
    // addresses even after close().
    assertEquals(listenAddress, ssc.socket().getLocalSocketAddress());

    // As per docs and RI - socket local address methods return the wildcard address before
    // bind() and after close(), but the port will be the same as it was before close().
    InetSocketAddress inLocalAddressAfterClose =
            (InetSocketAddress) in.socket().getLocalSocketAddress();
    assertTrue(inLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(inLocalAddress.getPort(), inLocalAddressAfterClose.getPort());

    InetSocketAddress outLocalAddressAfterClose =
            (InetSocketAddress) out.socket().getLocalSocketAddress();
    assertTrue(outLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(outLocalAddress.getPort(), outLocalAddressAfterClose.getPort());
}
 
Example 19
Source File: Server.java    From learning-code with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    final int port = 6789;
    // 1. 打开 ServerSocketChannel 用来监听客户端连接请求
    ServerSocketChannel channel = ServerSocketChannel.open();
    ServerSocket socket = channel.socket();
    socket.bind(new InetSocketAddress(port));
    // 2. 设置非祖塞模式
    channel.configureBlocking(false);
    Selector selector = Selector.open();
    // 3. 将 ServerSocketChannel 注册到 Selector 上,并且监听 ACCEPT 事件
    channel.register(selector, SelectionKey.OP_ACCEPT);

    // 缓冲区,设置大小 1M
    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    while (true) {
        int select = selector.select();
        // 4. 判断是否就绪,如果什么消息也没有则什么也不做
        if (select == 0) {
            continue;
        }
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        // 5. 如果有消息, 处理新的请求,
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();
            iterator.remove();
            if (!selectionKey.isValid()) {
                continue;
            }
            // 6. 判断是否有可以接受的连接,有的话创建连接
            if (selectionKey.isAcceptable()) {
                ServerSocketChannel acceptChannel = (ServerSocketChannel) selectionKey.channel();
                // 7. 创建客户端连接连接,并且设置非阻塞模式,将连接注册到 Selector 上,监听读操作,
                SocketChannel acceptSocket = acceptChannel.accept();
                acceptSocket.configureBlocking(false);
                acceptSocket.register(selector, SelectionKey.OP_READ);
            }
            // 8. 判断该消息是否可以读
            else if (selectionKey.isReadable()) {
                //9. 开始读取数据
                SocketChannel readChannel = (SocketChannel) selectionKey.channel();
                byteBuffer.clear();
                while (readChannel.read(byteBuffer) > 0) {
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()) {
                        // 解码
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(bytes);
                        String message = new String(bytes, StandardCharsets.UTF_8);
                        System.out.println(message);
                    }
                }
                byteBuffer.clear();
            }
        }
    }
}
 
Example 20
Source File: NioEchoServer.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务器。
 * 
 * @param port 服务监听的端口
 * @param selectTimeout {@link Selector}检查通道就绪状态的超时时间(单位:毫秒)
 */
private static void startServer(int port, int selectTimeout) {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(port));
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        while (true) {
            int selectNum = selector.select(selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isAcceptable()) {
                    acceptNew(selector, selectionKey);
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isReadable()) {
                    readData(selector, selectionKey);
                }
                
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}