Code example for ServerSocketChannel

Methods: close, configureBlocking, register, sleep, socket

0
    static class Server { 
        private ServerSocketChannel serverChannel = ServerSocketChannel.open();
        private ServerSocket socket = null;
 
        Server() throws Exception { 
            serverChannel.configureBlocking(false);
        } 
 
        public void initialize() throws Exception { 
            this.socket = serverChannel.socket();
            socket.bind(new InetSocketAddress("localhost", 0));
        } 
 
        public int getPort() { 
            return socket.getLocalPort();
        } 
 
        public boolean isOpen() { 
            return !socket.isClosed();
        } 
 
        public ServerSocketChannel getServerChannel() {
            return serverChannel;
        } 
 
        public void accept() { 
            Thread serverThread = new Thread(new Runnable() {
                public void run() { 
                    try { 
                        while (serverChannel.accept() == null) {
                            Thread.sleep(1000);
                        } 
                    } catch (Exception e) {}
                } 
            }); 
            serverThread.start();
        } 
 
        public void close() throws Exception{ 
            serverChannel.close();
        } 
    } 
 
    public void testSelectorAcceptAndRead() throws Exception { 
        Selector sel0 = Selector.open();
        Selector sel1 = Selector.open();
        Server server = new Server();
        SelectableChannel serverChannel = server.getServerChannel();
        SelectionKey mkey0 = serverChannel.register(sel0, SelectionKey.OP_ACCEPT);
        serverChannel.register(sel1, SelectionKey.OP_ACCEPT);
 
        // HUP is treating as acceptable 
        assertEquals(1, sel0.select(100));
        assertEquals(true, sel0.selectedKeys().contains(mkey0));
        server.initialize();
        // after bind can not accept 
        assertEquals(0, sel1.select(100));
        server.accept();
        Thread.sleep(1000);
        int port = server.getPort();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        Selector sel2 = Selector.open();
        socketChannel.register(sel2, SelectionKey.OP_WRITE);
        boolean isConnected = socketChannel.connect(new InetSocketAddress("localhost", port));
        if (!isConnected) {
            socketChannel.finishConnect();
        } 
 
        assertEquals(true, socketChannel.isConnected());
        server.close();
        Thread.sleep(3000);
        assertEquals(true, socketChannel.isConnected());
        assertEquals(1, sel2.select(100));
    } 
 
    public void testSelectUnConnectedChannel() throws Exception {