Java Code Examples for java.nio.channels.SelectionKey#isAcceptable()

The following examples show how to use java.nio.channels.SelectionKey#isAcceptable() . 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: CULNetworkHandlerImpl.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private void processSelectedKeys(Set<SelectionKey> keys) throws Exception {
    Iterator<SelectionKey> itr = keys.iterator();
    while (itr.hasNext()) {
        SelectionKey key = itr.next();
        if (key.isReadable()) {
            processRead(key);
        }
        if (key.isWritable()) {
            processWrite(key);
        }
        if (key.isConnectable()) {
            processConnect(key);
        }
        if (key.isAcceptable()) {
            ;
        }
        itr.remove();
    }
}
 
Example 2
Source File: HTTPAcceptHandler.java    From AdditionsAPI with MIT License 6 votes vote down vote up
@Override
public void handleSelection(SelectionKey selectionKey)
{
	try
	{
		if(selectionKey.isAcceptable())
		{				
			SocketChannel client = ((ServerSocketChannel)selectionKey.channel()).accept();
			client.configureBlocking(false);
			
			HTTPRequest request = new HTTPRequest(server);
			SelectionKey key = server.readPool.getLightest().register(client, request);
			
			server.timer.putTimer(key, Calendar.getInstance().getTimeInMillis() + server.timeOut);
			
			if(server.info)
			{
				Debug.sayTrue("HTTP connect: " + client.getRemoteAddress().toString());
			}
		}
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
}
 
Example 3
Source File: NIOAcceptor.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++acceptCount;
		try {
			selector.select( 1000L ); 
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					if (key.isValid() && key.isAcceptable()) {
						accept();							
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Throwable e) {
			LOGGER.warn(getName(), e);
		}
	}
}
 
Example 4
Source File: ConnectionAcceptor.java    From bt with Apache License 2.0 6 votes vote down vote up
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isAcceptable())
	{
		while(true)
		{
			SocketChannel chan = channel.accept();
			if(chan == null)
				break;
			
			if(!acceptor.test(chan))
			{
				chan.close();
				continue;
			}
		}

	}
}
 
Example 5
Source File: EchoServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Selector selector = Selector.open();
    ServerSocketChannel serverSocket = ServerSocketChannel.open();
    serverSocket.bind(new InetSocketAddress("localhost", 5454));
    serverSocket.configureBlocking(false);
    serverSocket.register(selector, SelectionKey.OP_ACCEPT);
    ByteBuffer buffer = ByteBuffer.allocate(256);

    while (true) {
        selector.select();
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext()) {

            SelectionKey key = iter.next();

            if (key.isAcceptable()) {
                register(selector, serverSocket);
            }

            if (key.isReadable()) {
                answerWithEcho(buffer, key);
            }
            iter.remove();
        }
    }
}
 
Example 6
Source File: MockServer.java    From xenqtt with Apache License 2.0 5 votes vote down vote up
/**
 * @param timeoutSeconds
 *            Seconds to wait for a client
 * @return The new client's {@link SocketChannel}. Null if the wait times out
 */
public SocketChannel nextClient(int timeoutSeconds) {

	long now = System.currentTimeMillis();
	long maxMillis = (timeoutSeconds * 1000);
	long end = now + maxMillis;
	long sleepMillis = maxMillis;

	try {
		while (sleepMillis > 0) {
			selector.select(sleepMillis);
			Set<SelectionKey> keys = selector.selectedKeys();
			for (SelectionKey key : keys) {
				if (key.isAcceptable()) {
					keys.clear();
					return ssc.accept();
				}
			}
			keys.clear();
			now = System.currentTimeMillis();
			sleepMillis = end - now;
		}
	} catch (IOException e) {
		throw new RuntimeException("crap", e);
	}

	return null;
}
 
Example 7
Source File: TestMessageIO.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static boolean awaitOp(Selector selector, SelectionKey key, int op) throws IOException {
    long end = System.currentTimeMillis() + SELECTION_TIMEOUT_MS;
    boolean selected = false;
    while (!selected) {
        // Check timeout
        long remaining = end - System.currentTimeMillis();
        if (remaining < 0) {
            break;
        }

        // Select up to remaining millis
        selector.select(remaining);

        // Handle op if possible
        switch (op) {
        case SelectionKey.OP_READ:
            selected |= key.isReadable();
            break;
        case SelectionKey.OP_ACCEPT:
            selected |= key.isAcceptable();
            break;
        case SelectionKey.OP_WRITE:
            selected |= key.isWritable();
            break;
        case SelectionKey.OP_CONNECT:
            selected |= key.isConnectable();
            break;
        }
    }
    return selected;
}
 
Example 8
Source File: SocketServer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void process( SelectionKey key ) throws IOException {
    if ( key.isAcceptable() ){
        acceptConnection(key);
    }
    else {
        super.process(key);
    }
}
 
Example 9
Source File: SocketTunnel.java    From AgentX with Apache License 2.0 5 votes vote down vote up
public void handleEvent(SelectionKey key) {
    if (key.isAcceptable())
        buildConnection(key);

    else if (key.isReadable())
        transferData(key);
}
 
Example 10
Source File: OioSctpServerChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    if (!isActive()) {
        return -1;
    }

    SctpChannel s = null;
    int acceptedChannels = 0;
    try {
        final int selectedKeys = selector.select(SO_TIMEOUT);
        if (selectedKeys > 0) {
            final Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
            for (;;) {
                SelectionKey key = selectionKeys.next();
                selectionKeys.remove();
                if (key.isAcceptable()) {
                    s = sch.accept();
                    if (s != null) {
                        buf.add(new OioSctpChannel(this, s));
                        acceptedChannels ++;
                    }
                }
                if (!selectionKeys.hasNext()) {
                    return acceptedChannels;
                }
            }
        }
    } catch (Throwable t) {
        logger.warn("Failed to create a new channel from an accepted sctp channel.", t);
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t2) {
                logger.warn("Failed to close a sctp channel.", t2);
            }
        }
    }

    return acceptedChannels;
}
 
Example 11
Source File: ChannelDispatcher.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void selectServerSocketKeys() throws IOException {
    int numSelected = serverSocketSelector.select(timeout);
    if (numSelected == 0) {
        return;
    }

    // for each registered server socket - see if any connections are waiting to be established
    final Iterator<SelectionKey> itr = serverSocketSelector.selectedKeys().iterator();
    while (itr.hasNext()) {
        SelectionKey serverSocketkey = itr.next();
        final SelectableChannel channel = serverSocketkey.channel();
        AbstractChannelReader reader = null;
        if (serverSocketkey.isValid() && serverSocketkey.isAcceptable()) {
            final ServerSocketChannel ssChannel = (ServerSocketChannel) serverSocketkey.channel();
            final SocketChannel sChannel = ssChannel.accept();
            if (sChannel != null) {
                sChannel.configureBlocking(false);
                final SelectionKey socketChannelKey = sChannel.register(socketChannelSelector, SelectionKey.OP_READ);
                final String readerId = sChannel.socket().toString();
                reader = new SocketChannelReader(readerId, socketChannelKey, emptyBuffers, factory);
                final ScheduledFuture<?> readerFuture = executor.scheduleWithFixedDelay(reader, 10L,
                        channelReaderFrequencyMilliseconds.get(), TimeUnit.MILLISECONDS);
                reader.setScheduledFuture(readerFuture);
                socketChannelKey.attach(reader);
            }
        }
        itr.remove(); // do this so that the next select operation returns a positive value; otherwise, it will return 0.
        if (reader != null && LOGGER.isDebugEnabled()) {
            LOGGER.debug(this + " New Connection established.  Server channel: " + channel + " Reader: " + reader);
        }
    }
}
 
Example 12
Source File: TThreadedSelectorServer.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately: If there are connections to
 * be accepted, accept them.
 */
private void select() {
  try {
    // wait for connect events.
    acceptSelector.select();

    // process the io events we received
    Iterator<SelectionKey> selectedKeys = acceptSelector.selectedKeys().iterator();
    while (!stopped_ && selectedKeys.hasNext()) {
      SelectionKey key = selectedKeys.next();
      selectedKeys.remove();

      // skip if not valid
      if (!key.isValid()) {
        continue;
      }

      if (key.isAcceptable()) {
        handleAccept();
      } else {
        LOGGER.warn("Unexpected state in select! " + key.interestOps());
      }
    }
  } catch (IOException e) {
    LOGGER.warn("Got an IOException while selecting!", e);
  }
}
 
Example 13
Source File: OioSctpServerChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    if (!isActive()) {
        return -1;
    }

    SctpChannel s = null;
    int acceptedChannels = 0;
    try {
        final int selectedKeys = selector.select(SO_TIMEOUT);
        if (selectedKeys > 0) {
            final Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
            for (;;) {
                SelectionKey key = selectionKeys.next();
                selectionKeys.remove();
                if (key.isAcceptable()) {
                    s = sch.accept();
                    if (s != null) {
                        buf.add(new OioSctpChannel(this, s));
                        acceptedChannels ++;
                    }
                }
                if (!selectionKeys.hasNext()) {
                    return acceptedChannels;
                }
            }
        }
    } catch (Throwable t) {
        logger.warn("Failed to create a new channel from an accepted sctp channel.", t);
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t2) {
                logger.warn("Failed to close a sctp channel.", t2);
            }
        }
    }

    return acceptedChannels;
}
 
Example 14
Source File: NonBlockingServer.java    From netty.book.kor with MIT License 4 votes vote down vote up
private void startServer() throws IOException {
    // create selector and channel
    this.selector = Selector.open();
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    // bind to port
    InetSocketAddress listenAddr = new InetSocketAddress(this.addr, this.port);
    serverChannel.socket().bind(listenAddr);
    serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    // processing
    while (true) {
        // wait for events
        this.selector.select();

        // wakeup to work on selected keys
        Iterator<SelectionKey> keys = this.selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = (SelectionKey) keys.next();

            // this is necessary to prevent the same key from coming up
            // again the next time around.
            keys.remove();

            if (!key.isValid()) {
                continue;
            }

            if (key.isAcceptable()) {
                this.accept(key);
            }
            else if (key.isReadable()) {
                this.read(key);
            }
            else if (key.isWritable()) {
                this.write(key);
            }
        }
    }
}
 
Example 15
Source File: NonBlockingServer.java    From netty.book.kor with MIT License 4 votes vote down vote up
private void startEchoServer() {
   try (
      Selector selector = Selector.open();
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()
    ) {

      if ((serverSocketChannel.isOpen()) && (selector.isOpen())) {
         serverSocketChannel.configureBlocking(false);
         serverSocketChannel.bind(new InetSocketAddress(8888));

         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
         System.out.println("접속 대기중");

         while (true) {
            selector.select();
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

            while (keys.hasNext()) {
               SelectionKey key = (SelectionKey) keys.next();
               keys.remove();

               if (!key.isValid()) {
                  continue;
               }

               if (key.isAcceptable()) {
                  this.acceptOP(key, selector);
               }
               else if (key.isReadable()) {
                  this.readOP(key);
               }
               else if (key.isWritable()) {
                  this.writeOP(key);
               }
            }
         }
      }
      else {
         System.out.println("서버 소캣을 생성하지 못했습니다.");
      }
   }
   catch (IOException ex) {
      System.err.println(ex);
   }
}
 
Example 16
Source File: NioSelectorLoop.java    From TakinRPC with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

    while (running) {

        try {
            select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            if (selectionKeys.isEmpty()) {
                continue;
            }

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                final SelectionKey key = iterator.next();
                iterator.remove();

                if (!key.isValid()) {
                    continue;
                }

                if (key.isAcceptable()) {
                    doAccept(key);
                }

                if (key.isConnectable()) {
                    doConnect(key);
                }

                if (key.isValid() && key.isReadable()) {
                    doRead(key);
                }

                if (key.isValid() && key.isWritable()) {
                    doWrite(key);
                }
            }

        } catch (Throwable t) {
            LOGGER.warn("Unexpected exception in the selector loop.", t);

            // 睡眠1S, 防止连续的异常导致cpu消耗
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {
            }
        }
    }
}
 
Example 17
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 4 votes vote down vote up
private void startServer() throws Exception{
        //声明一个selector
        selector= SelectorProvider.provider().openSelector();

        //声明一个server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //声明服务器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服务器端的socket channel绑定在这个端口。
        ssc.socket().bind(isa);
        //把一个socketchannel注册到一个selector上,同时选择监听的事件,SelectionKey.OP_ACCEPT表示对selector如果
        //监听到注册在它上面的server socket channel准备去接受一个连接,或 有个错误挂起,selector将把OP_ACCEPT加到
        //key ready set 并把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
 
Example 18
Source File: TcpProxyServer.java    From NetBare with MIT License 4 votes vote down vote up
@Override
protected void process() throws IOException {
    int select = mSelector.select();
    if (select == 0) {
        return;
    }
    Set<SelectionKey> selectedKeys = mSelector.selectedKeys();
    if (selectedKeys == null) {
        return;
    }
    Iterator<SelectionKey> iterator = selectedKeys.iterator();
    while (iterator.hasNext()) {
        SelectionKey key = iterator.next();
        try {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    onAccept();
                } else {
                    Object attachment = key.attachment();
                    if (attachment instanceof NioCallback) {
                        NioCallback callback = (NioCallback) attachment;
                        try {
                            if (key.isConnectable()) {
                                callback.onConnected();
                            } else if (key.isReadable()) {
                                callback.onRead();
                            } else if (key.isWritable()) {
                                callback.onWrite();
                            }
                        } catch (IOException e) {
                            NioTunnel tunnel = callback.getTunnel();
                            String ip = null;
                            InetAddress address = ((Socket)tunnel.socket()).getInetAddress();
                            if (address != null) {
                                ip = address.getHostAddress();
                            }
                            if (!tunnel.isClosed()) {
                                handleException(e, ip);
                            }
                            callback.onClosed();
                        }
                    }
                }
            }
        } finally {
            iterator.remove();
        }

    }
}
 
Example 19
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);
    }
}
 
Example 20
Source File: Listener.java    From vespa with Apache License 2.0 4 votes vote down vote up
/**
 * Check channels for readiness and deal with channels that have
 * pending operations.
 */
private void selectLoop() {
    while (!Thread.currentThread().isInterrupted()) {
        processNewConnections();
        processModifyInterestOps();

        try {
            int n = selector.select();

            if (0 == n) {
                continue;
            }
        } catch (java.io.IOException e) {
            log.log(Level.WARNING, "error during select", e);
            return;
        }

        runSelectLoopPreHooks();

        Iterator<SelectionKey> i = selector.selectedKeys().iterator();

        while (i.hasNext()) {
            SelectionKey key = i.next();

            i.remove();

            if (!key.isValid()) {
                continue;
            }

            if (key.isReadable()) {
                performRead(key);
                if (!key.isValid()) {
                    continue;
                }
            }

            if (key.isWritable()) {
                performWrite(key);
                if (!key.isValid()) {
                    continue;
                }
            }

            if (key.isConnectable()) {
                performConnect(key);
                if (!key.isValid()) {
                    continue;
                }
            }

            if (key.isAcceptable()) {
                performAccept(key);
            }
        }

        runSelectLoopPostHooks();
    }
}