Package java.nio.channels

Examples of java.nio.channels.ServerSocketChannel


    return s;
  }

  private ServerSocketChannel checkChannel() throws IOException
  {
    ServerSocketChannel c = checkHandler().channel();
    if (c == null)
      throw new IOException( "c == null" );
    return c;
  }
View Full Code Here


                          channel.register(selector,SelectionKey.OP_CONNECT,null);
                        }
                      }
                      else if (o instanceof ServerSocketChannel)
                      {
                        ServerSocketChannel channel = (ServerSocketChannel)o;
                        channel.register(getSelector(),SelectionKey.OP_ACCEPT);
                      }
                      else if (o instanceof ChangeTask)
                      {
                        ((ChangeTask)o).run();
                      }
                      else
                        throw new IllegalArgumentException(o.toString());
                    }
                    catch (Exception e)
                    {
                      if (isRunning())
                        Log.warn(e);
                      else
                        Log.debug(e);
                    }
                    catch (Error e)
                    {
                      if (isRunning())
                        Log.warn(e);
                      else
                        Log.debug(e);
                    }
                  }
                }
                finally
                {
                  changes.clear();
                }
               
                long idle_next = 0;
                long retry_next = 0;
                long now=System.currentTimeMillis();
                synchronized (this)
                {
                    _idleTimeout.setNow(now);
                    _retryTimeout.setNow(now);
                    if (_lowResourcesConnections>0 && selector.keys().size()>_lowResourcesConnections)
                        _idleTimeout.setDuration(_lowResourcesMaxIdleTime);
                    else
                        _idleTimeout.setDuration(_maxIdleTime);
                    idle_next=_idleTimeout.getTimeToNext();
                    retry_next=_retryTimeout.getTimeToNext();
                }

                // workout how low to wait in select
                long wait = 1000L// not getMaxIdleTime() as the now value of the idle timers needs to be updated.
                if (idle_next >= 0 && wait > idle_next)
                    wait = idle_next;
                if (wait > 0 && retry_next >= 0 && wait > retry_next)
                    wait = retry_next;
   
                // Do the select.
                if (wait > 2) // TODO tune or configure this
                {
                    // If we are in pausing mode
                    if (_pausing)
                    {
                        try
                        {
                            Thread.sleep(__BUSY_PAUSE); // pause to reduce impact of  busy loop
                        }
                        catch(InterruptedException e)
                        {
                            Log.ignore(e);
                        }
                    }
                       
                    long before=now;
                    int selected=selector.select(wait);
                    now = System.currentTimeMillis();
                    _idleTimeout.setNow(now);
                    _retryTimeout.setNow(now);
                    _selects++;

                    // Look for JVM bugs over a monitor period.
                    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933
                    // http://bugs.sun.com/view_bug.do?bug_id=6693490
                    if (now>_monitorNext)
                    {
                        _selects=(int)(_selects*__MONITOR_PERIOD/(now-_monitorStart));
                        _pausing=_selects>__MAX_SELECTS;
                        if (_pausing)
                            _paused++;
                           
                        _selects=0;
                        _jvmBug=0;
                        _monitorStart=now;
                        _monitorNext=now+__MONITOR_PERIOD;
                    }
                   
                    if (now>_log)
                    {
                        if (_paused>0
                            Log.info(this+" Busy selector - injecting delay "+_paused+" times");

                        if (_jvmFix2>0)
                            Log.info(this+" JVM BUG(s) - injecting delay"+_jvmFix2+" times");

                        if (_jvmFix1>0)
                            Log.info(this+" JVM BUG(s) - recreating selector "+_jvmFix1+" times, canceled keys "+_jvmFix0+" times");

                        else if(Log.isDebugEnabled() && _jvmFix0>0)
                            Log.info(this+" JVM BUG(s) - canceled keys "+_jvmFix0+" times");
                        _paused=0;
                        _jvmFix2=0;
                        _jvmFix1=0;
                        _jvmFix0=0;
                        _log=now+60000;
                    }
                   
                    // If we see signature of possible JVM bug, increment count.
                    if (selected==0 && wait>10 && (now-before)<(wait/2))
                    {
                        // Increment bug count and try a work around
                        _jvmBug++;
                        if (_jvmBug>(__JVMBUG_THRESHHOLD))
                        {
                            try
                            {
                                if (_jvmBug==__JVMBUG_THRESHHOLD+1)
                                    _jvmFix2++;
                                   
                                Thread.sleep(__BUSY_PAUSE); // pause to avoid busy loop
                            }
                            catch(InterruptedException e)
                            {
                                Log.ignore(e);
                            }
                        }
                        else if (_jvmBug==__JVMBUG_THRESHHOLD)
                        {
                            synchronized (this)
                            {
                                // BLOODY SUN BUG !!!  Try refreshing the entire selector.
                                _jvmFix1++;
                               
                                final Selector new_selector = Selector.open();
                                Iterator iterator = _selector.keys().iterator();
                                while (iterator.hasNext())
                                {
                                    SelectionKey k = (SelectionKey)iterator.next();
                                    if (!k.isValid() || k.interestOps()==0)
                                        continue;
                                   
                                    final SelectableChannel channel = k.channel();
                                    final Object attachment = k.attachment();
                                   
                                    if (attachment==null)
                                        addChange(channel);
                                    else
                                        addChange(channel,attachment);
                                }
                                Selector old_selector=_selector;
                                _selector=new_selector;
                                try
                                {
                                    old_selector.close();
                                }
                                catch(Exception e)
                                {
                                    Log.warn(e);
                                }
                                return;
                            }
                        }
                        else if (_jvmBug%32==31) // heuristic attempt to cancel key 31,63,95,... loops
                        {
                            // Cancel keys with 0 interested ops
                            int cancelled=0;
                            Iterator iter = selector.keys().iterator();
                            while(iter.hasNext())
                            {
                                SelectionKey k = (SelectionKey) iter.next();
                                if (k.isValid()&&k.interestOps()==0)
                                {
                                    k.cancel();
                                    cancelled++;
                                }
                            }
                            if (cancelled>0)
                                _jvmFix0++;
                           
                            return;
                        }
                    }
                    else if (__BUSY_KEY>0 && selected==1 && _selects>__MAX_SELECTS)
                    {
                        // Look for busy key
                        SelectionKey busy = (SelectionKey)selector.selectedKeys().iterator().next();
                        if (busy==_busyKey)
                        {
                            if (++_busyKeyCount>__BUSY_KEY && !(busy.channel() instanceof ServerSocketChannel))
                            {
                                final SelectChannelEndPoint endpoint = (SelectChannelEndPoint)busy.attachment();
                                Log.warn("Busy Key "+busy.channel()+" "+endpoint);
                                busy.cancel();
                                if (endpoint!=null)
                                {
                                    dispatch(new Runnable()
                                    {
                                        public void run()
                                        {
                                            try
                                            {
                                                endpoint.close();
                                            }
                                            catch (IOException e)
                                            {
                                                Log.ignore(e);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                        else
                            _busyKeyCount=0;
                        _busyKey=busy;
                    }
                }
                else
                {
                    selector.selectNow();
                    _selects++;
                }

                // have we been destroyed while sleeping
                if (_selector==null || !selector.isOpen())
                    return;

                // Look for things to do
                Iterator iter = selector.selectedKeys().iterator();
                while (iter.hasNext())
                {
                    key = (SelectionKey) iter.next();
                                       
                    try
                    {
                        if (!key.isValid())
                        {
                            key.cancel();
                            SelectChannelEndPoint endpoint = (SelectChannelEndPoint)key.attachment();
                            if (endpoint != null)
                                endpoint.doUpdateKey();
                            continue;
                        }
                       
                        Object att = key.attachment();
                       
                        if (att instanceof SelectChannelEndPoint)
                        {
                            SelectChannelEndPoint endpoint = (SelectChannelEndPoint)att;
                            endpoint.dispatch();
                        }
                        else if (key.isAcceptable())
                        {
                            SocketChannel channel = acceptChannel(key);
                            if (channel==null)
                                continue;

                            channel.configureBlocking(false);

                            // TODO make it reluctant to leave 0
                            _nextSet=++_nextSet%_selectSet.length;

                            // Is this for this selectset
                            if (_nextSet==_setID)
                            {
                                // bind connections to this select set.
                                SelectionKey cKey = channel.register(_selectSet[_nextSet].getSelector(), SelectionKey.OP_READ);
                                SelectChannelEndPoint endpoint=newEndPoint(channel,_selectSet[_nextSet],cKey);
                                cKey.attach(endpoint);
                                if (endpoint != null)
                                    endpoint.dispatch();
                            }
                            else
                            {
                                // nope - give it to another.
                                _selectSet[_nextSet].addChange(channel);
                                _selectSet[_nextSet].wakeup();
                            }
                        }
                        else if (key.isConnectable())
                        {
                            // Complete a connection of a registered channel
                            SocketChannel channel = (SocketChannel)key.channel();
                            boolean connected=false;
                            try
                            {
                                connected=channel.finishConnect();
                            }
                            catch(Exception e)
                            {
                                connectionFailed(channel,e,att);
                            }
View Full Code Here

            logger.info("Starting Encrypted Messaging Service on SSL port {}", DatabaseDescriptor.getSSLStoragePort());
        }

        if (DatabaseDescriptor.getServerEncryptionOptions().internode_encryption != ServerEncryptionOptions.InternodeEncryption.all)
        {
            ServerSocketChannel serverChannel = null;
            try
            {
                serverChannel = ServerSocketChannel.open();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            ServerSocket socket = serverChannel.socket();
            try
            {
                socket.setReuseAddress(true);
            }
            catch (SocketException e)
View Full Code Here

            ExecutorService executor = Executors.newCachedThreadPool();
            boolean success;
            long startTime;
            int interestOps;

            ServerSocketChannel ch = null;
            SelectorLoop loop = null;

            try {
                // Open a channel.
                ch = ServerSocketChannel.open();

                // Configure the channel
                try {
                    ch.socket().bind(new InetSocketAddress(0));
                    ch.configureBlocking(false);
                } catch (IOException e) {
                    logger.warn("Failed to configure a temporary socket.", e);
                    return -1;
                }

                // Prepare the selector loop.
                try {
                    loop = new SelectorLoop();
                } catch (IOException e) {
                    logger.warn("Failed to open a temporary selector.", e);
                    return -1;
                }

                // Register the channel
                try {
                    ch.register(loop.selector, 0);
                } catch (ClosedChannelException e) {
                    logger.warn("Failed to register a temporary selector.", e);
                    return -1;
                }

                SelectionKey key = ch.keyFor(loop.selector);

                // Start the selector loop.
                executor.execute(loop);

                // Level 0
                success = true;
                for (int i = 0; i < 10; i ++) {

                    // Increase the probability of calling interestOps
                    // while select() is running.
                    do {
                        while (!loop.selecting) {
                            Thread.yield();
                        }

                        // Wait a little bit more.
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            // Ignore
                        }
                    } while (!loop.selecting);

                    startTime = System.nanoTime();
                    key.interestOps(key.interestOps() | SelectionKey.OP_ACCEPT);
                    key.interestOps(key.interestOps() & ~SelectionKey.OP_ACCEPT);

                    if (System.nanoTime() - startTime >= 500000000L) {
                        success = false;
                        break;
                    }
                }

                if (success) {
                    constraintLevel = 0;
                } else {
                    // Level 1
                    success = true;
                    for (int i = 0; i < 10; i ++) {

                        // Increase the probability of calling interestOps
                        // while select() is running.
                        do {
                            while (!loop.selecting) {
                                Thread.yield();
                            }

                            // Wait a little bit more.
                            try {
                                Thread.sleep(50);
                            } catch (InterruptedException e) {
                                // Ignore
                            }
                        } while (!loop.selecting);

                        startTime = System.nanoTime();
                        interestOps = key.interestOps();
                        synchronized (loop) {
                            loop.selector.wakeup();
                            key.interestOps(interestOps | SelectionKey.OP_ACCEPT);
                            key.interestOps(interestOps & ~SelectionKey.OP_ACCEPT);
                        }

                        if (System.nanoTime() - startTime >= 500000000L) {
                            success = false;
                            break;
                        }
                    }
                    if (success) {
                        constraintLevel = 1;
                    } else {
                        constraintLevel = 2;
                    }
                }
            } catch (IOException e) {
                return -1;
            } finally {
                if (ch != null) {
                    try {
                        ch.close();
                    } catch (IOException e) {
                        logger.warn("Failed to close a temporary socket.", e);
                    }
                }
View Full Code Here

     * Regression test for Harmony-1947.
     */
    public void test_finishConnect() throws Exception {
        SocketAddress address = new InetSocketAddress("localhost", 0);

        ServerSocketChannel theServerChannel = ServerSocketChannel.open();
        ServerSocket serversocket = theServerChannel.socket();
        serversocket.setReuseAddress(true);
        // Bind the socket
        serversocket.bind(address);

        boolean doneNonBlockingConnect = false;
View Full Code Here

   
    public void testReadByteBuffer_Direct2() throws IOException {
        byte[] request = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        ByteBuffer buffer = ByteBuffer.allocateDirect(128);

        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(
                new InetSocketAddress(InetAddress.getLocalHost(), 0), 5);
        Socket client = new Socket(InetAddress.getLocalHost(), server.socket()
                .getLocalPort());
        client.setTcpNoDelay(false);
        Socket worker = server.socket().accept();
        SocketChannel workerChannel = worker.getChannel();

        OutputStream out = client.getOutputStream();
        out.write(request);
        out.close();

        buffer.limit(5);
        int bytesRead = workerChannel.read(buffer);
        assertEquals(5, bytesRead);
        assertEquals(5, buffer.position());

        buffer.limit(request.length);
        bytesRead = workerChannel.read(buffer);
        assertEquals(6, bytesRead);

        buffer.flip();
        assertEquals(request.length, buffer.limit());

        assertEquals(ByteBuffer.wrap(request), buffer);

        client.close();
        worker.close();
        server.close();
    }
View Full Code Here

    /**
     * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
     */
    public void test_writev() throws Exception {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(localAddr2);
        SocketChannel sc = SocketChannel.open();
        sc.connect(localAddr2);
        SocketChannel sock = ssc.accept();
        ByteBuffer[] buf = { ByteBuffer.allocate(10), ByteBuffer.allocateDirect(20) };

        while (buf[0].remaining() != 0 && buf[1].remaining() !=0) {
            assertTrue(sc.write(buf, 0, 2) >= 0);
        }

        ByteBuffer target = ByteBuffer.allocate(30);

        while (target.remaining() != 0) {
            assertTrue(sock.read(target) >=0);
        }

        ssc.close();
        sc.close();
        sock.close();
    }
View Full Code Here

    /**
     * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
     */
    public void test_write$LByteBuffer2() throws IOException {
        // Set-up
        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(null);
        SocketChannel client = SocketChannel.open();
        client.connect(server.socket().getLocalSocketAddress());
        SocketChannel worker = server.accept();

        // Test overlapping buffers
        byte[] data = "Hello world!".getBytes("UTF-8");
        ByteBuffer[] buffers = new ByteBuffer[3];
        buffers[0] = ByteBuffer.wrap(data, 0, 6);
        buffers[1] = ByteBuffer.wrap(data, 6, data.length - 6);
        buffers[2] = ByteBuffer.wrap(data);

        // Write them out, read what we wrote and check it
        client.write(buffers);
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        worker.read(readBuffer);
        readBuffer.flip();
        Buffer expected = ByteBuffer.allocate(1024).put(data).put(data).flip();
        assertEquals(expected, readBuffer);

        // Tidy-up
        worker.close();
        client.close();
        server.close();
    }
View Full Code Here

    /**
     * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
     */
    public void test_write$LByteBuffer_buffers() throws IOException {
        // Set-up
        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(null);
        SocketChannel client = SocketChannel.open();
        client.connect(server.socket().getLocalSocketAddress());
        SocketChannel worker = server.accept();

        // A variety of buffer types to write
        byte[] data = "Hello world!".getBytes("UTF-8");
        ByteBuffer[] buffers = new ByteBuffer[3];
        buffers[0] = ByteBuffer.wrap(data, 0, 2);
        assertFalse(buffers[0].isDirect());
        assertTrue(buffers[0].hasArray());

        buffers[1] = ByteBuffer.wrap(data, 2, 4).asReadOnlyBuffer();
        assertFalse(buffers[1].isDirect());
        assertFalse(buffers[1].hasArray());

        buffers[2] = ByteBuffer.allocateDirect(42);
        buffers[2].put(data, 6, data.length - 6);
        buffers[2].flip();
        assertTrue(buffers[2].isDirect());
        assertFalse(buffers[2].hasArray());

        // Write them out, read what we wrote and check it
        client.write(buffers);
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        worker.read(readBuffer);
        readBuffer.flip();
        assertEquals(ByteBuffer.wrap(data), readBuffer);

        // Tidy-up
        worker.close();
        client.close();
        server.close();
    }
View Full Code Here

    /**
     * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
     */
    public void test_write$LByteBuffer_writes() throws IOException {
        // Set-up
        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(null);
        SocketChannel client = SocketChannel.open();
        client.connect(server.socket().getLocalSocketAddress());
        SocketChannel worker = server.accept();

        // Data to write
        byte[] data = "Hello world!".getBytes("UTF-8");
        ByteBuffer[] buffers = new ByteBuffer[3];
        buffers[0] = ByteBuffer.wrap(data, 0, 6);
        buffers[1] = ByteBuffer.wrap("world!".getBytes("UTF-8"));
        buffers[2] = buffers[0];
        assertTrue(buffers[0].hasArray());

        // Test a sequence of write calls
        client.write(buffers, 0, 0); // write nothing
        client.write(buffers, 1, 0); // write nothing
        client.write(buffers, 0, 1); // write "Hello "
        assertEquals("Failed to drain buffer 0", 0, buffers[0].remaining());
        assertEquals("Shouldn't touch buffer 1", buffers[1].limit(), buffers[1]
                .remaining());
        client.write(buffers, 0, 2); // writes "world!"
        assertEquals("Failed to drain buffer 1", 0, buffers[1].remaining());
        client.write(buffers, 0, 3); // write nothing

        // Read what we wrote and check it
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        worker.read(readBuffer);
        readBuffer.flip();
        assertEquals(ByteBuffer.wrap(data), readBuffer);

        // Tidy-up
        worker.close();
        client.close();
        server.close();
    }
View Full Code Here

TOP

Related Classes of java.nio.channels.ServerSocketChannel

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.