private void onChannelAcceptable(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); readKey.attach(key.attachment()); }
private KafkaChannel buildAndAttachKafkaChannel(SocketChannel socketChannel, String id, SelectionKey key) throws IOException { try { KafkaChannel channel = channelBuilder.buildChannel(id, key, maxReceiveSize, memoryPool); key.attach(channel); return channel; } catch (Exception e) { try { socketChannel.close(); } finally { key.cancel(); } throw new IOException("Channel could not be created for socket " + socketChannel, e); } }
@Override protected void doBeginRead() throws Exception { // Channel.read() or ChannelHandlerContext.read() was called final SelectionKey selectionKey = this.selectionKey; if (!selectionKey.isValid()) { return; } readPending = true; final int interestOps = selectionKey.interestOps(); if ((interestOps & readInterestOp) == 0) { selectionKey.interestOps(interestOps | readInterestOp); } }
iterator.remove(); try { if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate()); System.out.println( "Accepted connection from " + client); if (key.isWritable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = (ByteBuffer) key.attachment(); while (buffer.hasRemaining()) { if (client.write(buffer) == 0) { break; key.cancel(); try { key.channel().close(); } catch (IOException cex) {
protected void start(boolean direct) throws Exception { selector=Selector.open(); ch=ServerSocketChannel.open(); ch.bind(new InetSocketAddress("0.0.0.0", 7500)); ch.configureBlocking(false); ch.register(selector, SelectionKey.OP_ACCEPT, null); System.out.println("-- server ready"); selector.select(); Set<SelectionKey> keys=selector.selectedKeys(); for(Iterator<SelectionKey> it=keys.iterator(); it.hasNext();) { SelectionKey key=it.next(); if(!key.isValid()) { it.remove(); continue; if(key.isAcceptable()) { SocketChannel client_ch=ch.accept(); if(client_ch != null) { // accept() may return null... System.out.printf("accepted connection from %s\n", client_ch.getRemoteAddress()); client_ch.configureBlocking(false); client_ch.register(selector, SelectionKey.OP_READ, create(SIZE, direct)); else if(key.isReadable()) { if(!handle((SocketChannel)key.channel(), (ByteBuffer)key.attachment())) { key.cancel(); Util.close(key.channel());
if (beatKey != null && beatKey.key.isValid()) { if (System.currentTimeMillis() - beatKey.birthTime < TCP_KEEP_ALIVE_MILLIS) { ipAddress.setBeingChecked(false); beatKey.key.cancel(); beatKey.key.channel().close(); channel = SocketChannel.open(); channel.configureBlocking(false); channel.socket().setSoLinger(false, -1); channel.socket().setReuseAddress(true); channel.socket().setKeepAlive(true); channel.socket().setTcpNoDelay(true); channel.connect(new InetSocketAddress(ipAddress.getIp(), port)); = channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); key.attach(beat); keyMap.put(beat.toString(), new BeatKey(key));
select.select(5000); Set<SelectionKey> keys = select.selectedKeys(); for (SelectionKey k : keys) { if (!k.isValid()) continue; if (k.isAcceptable() && k.channel() == socks) { SocketChannel csock = socks.accept(); continue; addClient(csock); csock.register(select, SelectionKey.OP_READ); } else if (k.isReadable()) { if (k.channel() == cl.client) // from client (e.g. socks client) cl.newClientData(select); else if (k.channel() == cl.remote) { // from server client is connected to (e.g. website) cl.newRemoteData(); cl.client.close(); if (cl.remote != null) cl.remote.close(); k.cancel(); clients.remove(cl);
Selector selector = Selector.open(); iter.remove(); switch (key.readyOps()) { case OP_ACCEPT: client = ((ServerSocketChannel) key.channel()).accept(); client.configureBlocking(false); client.register(selector, OP_READ); break; case OP_READ: client = (SocketChannel) key.channel(); buffer.clear(); if (client.read(buffer) != -1) { buffer.flip(); String line = new String(buffer.array(), buffer.position(), buffer.remaining()); k.cancel(); k.channel().close(); key.cancel(); System.out.println("unhandled " + key.readyOps()); break;
Selector selector = Selector.open(); int[] ports = {4000,4001,6000}; for (int port : ports) { ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind(new InetSocketAddress(port)); // we are only interested when accept evens occur on this socket server.register(selector, SelectionKey.OP_ACCEPT); } while (selector.isOpen()) { selector.select(); Set readyKeys = selector.selectedKeys(); Iterator iterator = readyKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); if (key.isAcceptable()) { SocketChannel client = server.accept(); Socket socket = client.socket(); // create new thread to deal with connection (closing both socket and client when done) } } } // tidy up selector and channels
Collections.shuffle(selectedList); for (SelectionKey k : selectedList) { if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) { SocketChannel sc = ((ServerSocketChannel) k .channel()).accept(); InetAddress ia = sc.socket().getInetAddress(); int cnxncount = getClientCnxnCount(ia); if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){ LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns ); sc.close(); } else { LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress()); SelectionKey.OP_READ); NIOServerCnxn cnxn = createConnection(sc, sk); sk.attach(cnxn); addCnxn(cnxn); } else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) { NIOServerCnxn c = (NIOServerCnxn) k.attachment(); c.doIO(k); } else { if (LOG.isDebugEnabled()) { LOG.debug("Unexpected ops in select " + k.readyOps());
private void run() throws IOException final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT); receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT)); final Selector selector = Selector.open(); while (selector.selectNow() == 0) final Set<SelectionKey> selectedKeys = selector.selectedKeys(); final Iterator<SelectionKey> iter = selectedKeys.iterator(); if (key.isReadable()) ((IntSupplier)key.attachment()).getAsInt();
void doAccept(SelectionKey key) throws InterruptedException, IOException, OutOfMemoryError { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel; while ((channel = server.accept()) != null) { channel.configureBlocking(false); channel.socket().setTcpNoDelay(tcpNoDelay); channel.socket().setKeepAlive(tcpKeepAlive); Reader reader = getReader(); SimpleServerRpcConnection c = connectionManager.register(channel); // If the connectionManager can't take it, close the connection. if (c == null) { if (channel.isOpen()) { IOUtils.cleanup(null, channel); } continue; } key.attach(c); // so closeCurrentConnection can get the object reader.addConnection(c); } }
private void selectServerSocketKeys() throws IOException { int numSelected = serverSocketSelector.select(timeout); if (numSelected == 0) { return; 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);
@Override void testableCloseSocket() throws IOException { LOG.info("testableCloseSocket() called"); // sockKey may be concurrently accessed by multiple // threads. We use tmp here to avoid a race condition SelectionKey tmp = sockKey; if (tmp!=null) { ((SocketChannel) tmp.channel()).socket().close(); } }
for (SelectionKey key: oldSelector.keys()) { Object a = key.attachment(); try { if (!key.isValid() || key.channel().keyFor(newSelectorTuple.unwrappedSelector) != null) { continue; int interestOps = key.interestOps(); key.cancel(); SelectionKey newKey = key.channel().register(newSelectorTuple.unwrappedSelector, interestOps, a); if (a instanceof AbstractNioChannel) { oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) {
this.selector.select(1000); Set<SelectionKey> selected = this.selector.selectedKeys(); if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) { SocketChannel sc = ((ServerSocketChannel) k.channel()).accept(); + sc.socket().getRemoteSocketAddress()); } catch (Exception e) { log.error("new HAConnection exception", e); sc.close(); log.warn("Unexpected ops in select " + k.readyOps());
public void run() { try { java.nio.channels.Selector acceptSelector = java.nio.channels.Selector.open(); serverSocketChannel.register(acceptSelector, SelectionKey.OP_ACCEPT); while (serverSocketChannel.isOpen()) { if (acceptSelector.select(1000) > 0) { Iterator<SelectionKey> it = acceptSelector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isAcceptable()) { SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept(); socketChannel.configureBlocking(false); newChannels.add(socketChannel); selector.wakeup(); } it.remove(); } } } } catch (IOException e) { // ignore } } }
protected void accept( SelectionKey key ) throws IOException { // Would only get accepts on a server channel ServerSocketChannel serverChan = (ServerSocketChannel)key.channel(); // Setup the connection to be non-blocking SocketChannel remoteChan = serverChan.accept(); remoteChan.configureBlocking(false); // And disable Nagle's buffering algorithm... we want // data to go when we put it there. Socket sock = remoteChan.socket(); sock.setTcpNoDelay(true); // Let the selector know we're interested in reading // data from the channel SelectionKey endKey = remoteChan.register( selector, SelectionKey.OP_READ ); // And now create a new endpoint NioEndpoint p = addEndpoint( remoteChan ); endKey.attach(p); endpointKeys.put(p, endKey); }
key.cancel(); return; SocketChannel channel = server.accept(); if(channel==null){ return; channel.configureBlocking( false ); Socket socket = channel.socket(); socket.setTcpNoDelay( isTcpNoDelay() ); socket.setKeepAlive( true ); WebSocketImpl w = wsf.createWebSocket( this, drafts ); w.setSelectionKey(channel.register( selector, SelectionKey.OP_READ, w )); try { w.setChannel( wsf.wrapChannel( channel, w.getSelectionKey() )); } catch (IOException ex) { if( w.getSelectionKey() != null ) w.getSelectionKey().cancel();