Search in sources :

Example 76 with Selector

use of java.nio.channels.Selector in project jeromq by zeromq.

the class Ctx method createSelector.

// Creates a Selector that will be closed when the context is destroyed.
public Selector createSelector() {
    try {
        Selector selector = Selector.open();
        assert (selector != null);
        selectors.add(selector);
        return selector;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 77 with Selector

use of java.nio.channels.Selector in project cradle by BingLau7.

the class PlainNioServer method serve.

public void serve(int port) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    ServerSocket ss = serverChannel.socket();
    // 将服务器绑定到选定端口
    InetSocketAddress address = new InetSocketAddress(port);
    ss.bind(address);
    // 打开 Selector 来处理 Channel
    Selector selector = Selector.open();
    // 将 ServerSocket 注册到 Selector 以接收连接
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
    for (; ; ) {
        try {
            /// 等到需要处理的新事件;阻塞将一直持续到下一个传入事件
            selector.select();
        } catch (IOException ex) {
            ex.printStackTrace();
            // handle exception
            break;
        }
        // 获取所有接收事件的 Selection-Key 实例
        Set<SelectionKey> readyKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            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;
                        }
                    }
                    // 关闭连接
                    client.close();
                }
            } catch (IOException ex) {
                key.cancel();
                try {
                    key.channel().close();
                } catch (IOException cex) {
                // ignore on close
                }
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 78 with Selector

use of java.nio.channels.Selector in project opennms by OpenNMS.

the class ConnectionTrackerTest method test.

@Test
@Ignore
public void test() throws IOException {
    Selector selector = Selector.open();
    assertTrue(selector.isOpen());
    selector.close();
    assertFalse(selector.isOpen());
    DatagramChannel c = DatagramChannel.open();
    DatagramSocket s = c.socket();
    s.setSoTimeout(1000);
    byte[] buf = new byte[1024];
    DatagramPacket p = new DatagramPacket(buf, 1024, InetAddress.getLocalHost(), 7);
    s.send(p);
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) DatagramChannel(java.nio.channels.DatagramChannel) Selector(java.nio.channels.Selector) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 79 with Selector

use of java.nio.channels.Selector in project robovm by robovm.

the class SelectorTest method testInterrupted.

// http://code.google.com/p/android/issues/detail?id=15388
public void testInterrupted() throws IOException {
    Selector selector = Selector.open();
    try {
        Thread.currentThread().interrupt();
        int count = selector.select();
        assertEquals(0, count);
    } finally {
        selector.close();
        // RoboVM note: Clear this thread's interrupted flag. Other tests may fail if we don't.
        Thread.interrupted();
    }
}
Also used : Selector(java.nio.channels.Selector)

Example 80 with Selector

use of java.nio.channels.Selector in project robovm by robovm.

the class SelectorTest method testManyWakeupCallsTriggerOnlyOneWakeup.

public void testManyWakeupCallsTriggerOnlyOneWakeup() throws Exception {
    final Selector selector = Selector.open();
    try {
        selector.wakeup();
        selector.wakeup();
        selector.wakeup();
        selector.select();
        // create a latch that will reach 0 when select returns
        final CountDownLatch selectReturned = new CountDownLatch(1);
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    selector.select();
                    selectReturned.countDown();
                } catch (IOException ignored) {
                }
            }
        });
        thread.start();
        // select doesn't ever return, so await() times out and returns false
        assertFalse(selectReturned.await(2, TimeUnit.SECONDS));
    } finally {
        selector.close();
    }
}
Also used : IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Selector(java.nio.channels.Selector)

Aggregations

Selector (java.nio.channels.Selector)85 SelectionKey (java.nio.channels.SelectionKey)43 IOException (java.io.IOException)26 SocketChannel (java.nio.channels.SocketChannel)24 InetSocketAddress (java.net.InetSocketAddress)17 ServerSocketChannel (java.nio.channels.ServerSocketChannel)17 ByteBuffer (java.nio.ByteBuffer)10 ClosedChannelException (java.nio.channels.ClosedChannelException)8 DatagramChannel (java.nio.channels.DatagramChannel)8 CancelledKeyException (java.nio.channels.CancelledKeyException)6 ClosedSelectorException (java.nio.channels.ClosedSelectorException)4 SelectableChannel (java.nio.channels.SelectableChannel)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Test (org.junit.Test)4 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)3 BigDecimal (java.math.BigDecimal)2 ConnectException (java.net.ConnectException)2 DatagramPacket (java.net.DatagramPacket)2 DatagramSocket (java.net.DatagramSocket)2 InetAddress (java.net.InetAddress)2