Search in sources :

Example 41 with Selector

use of java.nio.channels.Selector in project GIPC by pdewan.

the class NioClientExp method run.

public void run() {
    SelectionKey writeKey = null;
    try {
    // SocketChannel socketChannel = syncConnect(initRspHandler);
    // globalSocketChannel = socketChannel;
    // send(socketChannel, "Hello World".getBytes());
    // send(socketChannel, "Goodbye World".getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    while (true) {
        try {
            if (register) {
                // globalSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                globalSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                register = false;
            }
            // Process any pending changes
            synchronized (this.pendingChanges) {
                Iterator changes = this.pendingChanges.iterator();
                while (changes.hasNext()) {
                    ChangeRequest change = (ChangeRequest) changes.next();
                    switch(change.type) {
                        case ChangeRequest.CHANGEOPS:
                            SelectionKey key = change.socket.keyFor(this.selector);
                            key.interestOps(change.ops);
                            break;
                        case ChangeRequest.REGISTER:
                            // change.socket.configureBlocking(true);
                            SocketChannel sockChannel = change.socket;
                            int ops = change.ops;
                            Selector theSelector = selector;
                            sockChannel.register(theSelector, ops);
                            break;
                    }
                }
                this.pendingChanges.clear();
            }
            // Wait for an event one of the registered channels
            this.selector.select();
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                selectedKeys.remove();
                if (!key.isValid()) {
                    continue;
                }
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    this.finishConnection(key);
                }
                if (key.isReadable()) {
                    this.read(key);
                }
                if (key.isWritable()) {
                    writeKey = key;
                    // this.write(key);
                    this.serializedWrite(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) Iterator(java.util.Iterator) IOException(java.io.IOException) EOFException(java.io.EOFException) Selector(java.nio.channels.Selector)

Example 42 with Selector

use of java.nio.channels.Selector in project Mycat_plus by coderczp.

the class NIOConnector method run.

@Override
public void run() {
    int invalidSelectCount = 0;
    for (; ; ) {
        final Selector tSelector = this.selector;
        ++connectCount;
        try {
            long start = System.nanoTime();
            tSelector.select(1000L);
            long end = System.nanoTime();
            connect(tSelector);
            Set<SelectionKey> keys = tSelector.selectedKeys();
            if (keys.size() == 0 && (end - start) < SelectorUtil.MIN_SELECT_TIME_IN_NANO_SECONDS) {
                invalidSelectCount++;
            } else {
                try {
                    for (SelectionKey key : keys) {
                        Object att = key.attachment();
                        if (att != null && key.isValid() && key.isConnectable()) {
                            finishConnect(key, att);
                        } else {
                            key.cancel();
                        }
                    }
                } finally {
                    invalidSelectCount = 0;
                    keys.clear();
                }
            }
            if (invalidSelectCount > SelectorUtil.REBUILD_COUNT_THRESHOLD) {
                final Selector rebuildSelector = SelectorUtil.rebuildSelector(this.selector);
                if (rebuildSelector != null) {
                    this.selector = rebuildSelector;
                }
                invalidSelectCount = 0;
            }
        } catch (Exception e) {
            LOGGER.warn(name, e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 43 with Selector

use of java.nio.channels.Selector in project tutorials by eugenp.

the class EchoServer method main.

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();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 44 with Selector

use of java.nio.channels.Selector in project JavaBase by SkyScraperTwc.

the class NIOTcpClient method main.

public static void main(String[] args) throws IOException {
    Selector selector = Selector.open();
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel.register(selector, SelectionKey.OP_READ);
    socketChannel.connect(new InetSocketAddress(IP_ADDRESS, PORT));
    while (!socketChannel.finishConnect()) ;
    new Thread(new SendRunnable(socketChannel)).start();
    System.out.println("Connecting to " + IP_ADDRESS + " on " + PORT);
    while (true) {
        selector.select();
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();
            if (selectionKey.isReadable()) {
                SocketChannel channel = (SocketChannel) selectionKey.channel();
                StringBuilder sb = new StringBuilder();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                while (channel.read(byteBuffer) > 0) {
                    byteBuffer.flip();
                    sb.append(new String(byteBuffer.array()));
                    byteBuffer.clear();
                }
                System.out.println("[server] " + sb.toString());
            }
            iterator.remove();
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 45 with Selector

use of java.nio.channels.Selector in project spring-integration by spring-projects.

the class TcpNioConnectionTests method testMemoryLeak.

@Test
public void testMemoryLeak() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<>();
    this.executor.execute(() -> {
        try {
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket socket = server.accept();
            byte[] b = new byte[6];
            readFully(socket.getInputStream(), b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setNioHarvestInterval(100);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        Map<SocketChannel, TcpNioConnection> connections = factory.getConnections();
        assertEquals(1, connections.size());
        connection.close();
        assertTrue(!connection.isOpen());
        TestUtils.getPropertyValue(factory, "selector", Selector.class).wakeup();
        int n = 0;
        while (connections.size() > 0) {
            Thread.sleep(100);
            if (n++ > 100) {
                break;
            }
        }
        assertEquals(0, connections.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Unexpected exception " + e);
    }
    factory.stop();
    serverSocket.get().close();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocket(java.net.ServerSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Selector(java.nio.channels.Selector) Test(org.junit.Test)

Aggregations

Selector (java.nio.channels.Selector)186 SelectionKey (java.nio.channels.SelectionKey)84 IOException (java.io.IOException)70 SocketChannel (java.nio.channels.SocketChannel)51 InetSocketAddress (java.net.InetSocketAddress)38 ByteBuffer (java.nio.ByteBuffer)28 ServerSocketChannel (java.nio.channels.ServerSocketChannel)27 Test (org.junit.Test)14 DatagramChannel (java.nio.channels.DatagramChannel)13 ClosedChannelException (java.nio.channels.ClosedChannelException)12 CancelledKeyException (java.nio.channels.CancelledKeyException)11 NioEndpoint (org.apache.tomcat.util.net.NioEndpoint)10 ClosedSelectorException (java.nio.channels.ClosedSelectorException)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 EOFException (java.io.EOFException)7 ServerSocket (java.net.ServerSocket)7 SelectableChannel (java.nio.channels.SelectableChannel)7 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)5 Iterator (java.util.Iterator)5 MemberImpl (org.apache.catalina.tribes.membership.MemberImpl)5