Examples of SelectionKey


Examples of java.nio.channels.SelectionKey

            // Get selected keys
            Set<SelectionKey> selectedKeys = this.selector.selectedKeys();

            for (Iterator<SelectionKey> itSelectedKeys = selectedKeys.iterator(); itSelectedKeys.hasNext();) {
                SelectionKey selectionKey = itSelectedKeys.next();
                itSelectedKeys.remove(); // remove it has it was handled

                // Server key ?
                if (selectionKey == this.serverkey) {
                    // New client ?
                    if (selectionKey.isAcceptable()) {
                        try {
                            handleAccept();
                        } catch (Exception e) {
                            // all exception (including runtime)
                            logger.log(Level.SEVERE, "Unable to accept a new connection.", e);
                        }
                    }
                } else if (selectionKey.isReadable()) {
                    // get request from client
                    try {
                        handleRead(selectionKey);
                    } catch (Exception e) {
                        // all exception (including runtime)
                        logger.log(Level.SEVERE, "Unable to read data from the client.", e);
                    }
                } else if (selectionKey.isWritable()) {
                    // answer to the client
                    try {
                        handleWrite(selectionKey);
                    } catch (Exception e) {
                        // all exception (including runtime)
View Full Code Here

Examples of java.nio.channels.SelectionKey

                {
                    continue;
                }

                Iterator it = _selector.selectedKeys().iterator();
                SelectionKey selKey = null;
                SocketChannel cChannel = null;
                ConnectionHeader header = null;

                while ( it.hasNext() && !isInterrupted() )
                {
                    selKey = (SelectionKey) it.next();
                    it.remove();

                    try
                    {
                        // validate the key
                        if ( !selKey.isValid() )
                        {
                            continue;
                        }

                        // socket is ready for establishing a connection?
                        if ( selKey.isAcceptable() )
                        {
                            // establish the connection
                            cChannel = this._channel.accept();

                            // a little bit paranoia
View Full Code Here

Examples of java.nio.channels.SelectionKey

                    result = e;
                }
            }
            else
            {
                SelectionKey selKey = null;

                boolean error = false;

                try
                {
                    if ( this._channel == null || !this._channel.isOpen() )
                    {
                        log.log( Level.FINEST, "opening new connection" );
                        openSocketChannel();
                        _channel.register( this._selector, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE );
                    }
                    else
                    {
                        log.log( Level.FINEST, "reusing persistent connection" );
                        selKey = _channel.keyFor( this._selector );
                        // register this channel again
                        selKey = _channel.register( this._selector, 0 );
                        selKey.interestOps( SelectionKey.OP_WRITE );
                    }

                    Iterator it = null;

                    while ( this._selector.select( _connectionTimeout ) > 0 )
                    {
                        it = this._selector.selectedKeys().iterator();

                        while ( it.hasNext() )
                        {
                            selKey = (SelectionKey) it.next();
                            it.remove();

                            if ( !selKey.isValid() )
                            {
                                continue;
                            }

                            try
                            {
                                if ( selKey.isConnectable() && _channel.isConnectionPending() )
                                {
                                    if ( !_channel.finishConnect() )
                                    {
                                        continue;
                                    }

                                    clientInfo.setChannel( _channel );

                                    if ( log.isLoggable( Level.INFO ) )
                                    {
                                        log.log( Level.INFO, "Connection established to "
                                                + _channel.socket().getRemoteSocketAddress() );
                                    }

                                    _channel.register( this._selector, SelectionKey.OP_WRITE );
                                }
                                if ( selKey.isWritable() )
                                {
                                    if ( _serverInfo == null )
                                    {
                                        log.log( Level.FINEST, "Handshaking server..." );
                                        _serverInfo = DataChannel.getInstance().handshake( clientInfo, _channel,
                                                                                           _connectionTimeout );
                                        if ( _serverInfo == null )
                                        {
                                            throw new IOException( "Connection timeout (" + _connectionTimeout
                                                    + "ms) reached while waiting for handshake completing." );
                                        }
                                        else if ( clientInfo.isHttp() && !_serverInfo.isHttp() )
                                        {
                                            throw new UnsupportedOperationException(
                                                                                     "The server does not permit usage of HTTP packaging!" );
                                        }
                                    }

                                    if ( _serverInfo.hasNonBlockingReadWrite() )
                                    {
                                        send( _serverInfo, clientInfo, selKey, obj );
                                        _channel.register( this._selector, SelectionKey.OP_READ );
                                    }
                                    else
                                    {
                                        selKey.cancel();
                                        _channel.configureBlocking( true );
                                        result = processBlocked( clientInfo, obj );

                                        if ( result != null && (result instanceof Throwable) )
                                        {
                                            if ( !(result instanceof RemoteException) )
                                            {
                                                throw new RemoteException(
                                                                           "The server did return an Exception while handling your request!",
                                                                           (Throwable) result );
                                            }
                                            else
                                            {
                                                throw (RemoteException) result;
                                            }
                                        }

                                        return result;
                                    }
                                }
                                else if ( selKey.isReadable() )
                                {
                                    result = receive( clientInfo );
                                    selKey.cancel();

                                    if ( result != null && (result instanceof Throwable) )
                                    {
                                        if ( !(result instanceof RemoteException) )
                                        {
                                            throw new RemoteException(
                                                                       "The server did return an Exception while handling your request!",
                                                                       (Throwable) result );
                                        }
                                        else
                                        {
                                            throw (RemoteException) result;
                                        }
                                    }

                                    return result;
                                }
                            }
                            catch ( IncompleteIOException ioe )
                            {
                                // selKey.cancel();
                                if ( ioe.getIOBuffer() != null )
                                {
                                    clientInfo.setWaitingBuffer( ioe.getIOBuffer() );
                                    _channel.register( this._selector, ioe.getSelectionInterest() );
                                }
                                else
                                {
                                    // rethrow origin exception to inform the caller
                                    // without the hassle of nested exceptions
                                    throw ioe;
                                }
                            }
                            catch ( ParseException e )
                            {
                                error = true;
                                throw new IOException(
                                                       "Connection closed due to unparseable connection header! Exact message was: "
                                                               + e.getMessage() );
                            }
                            catch ( IOException e )
                            {
                                if ( !(e instanceof RemoteException) )
                                {
                                    error = true;
                                }
                                // rethrow origin exception to inform the caller
                                // without the hassle of nested exceptions
                                throw e;
                            }
                        }
                    }
                }
                finally
                {
                    selKey.cancel();
                    // beeing a little bit paranoid is sometimes better
                    clientInfo.releaseAttachment();
                    clientInfo.releaseWaitingBuffer();
                    if ( _serverInfo != null )
                    {
View Full Code Here

Examples of java.nio.channels.SelectionKey

        try
        {
            Iterator it;
            SocketChannel cChannel;
            SelectionKey selKey;
            ConnectionHeader clientInfo;
            Set keys;

            while ( !isInterrupted() )
            {
                this._load = 0;

                // (pre)register interested socket channels
                registerAspirants();

                // just try endless new selects until there are interested
                // socket channels
                if ( _selector.select() == 0 ) continue;

                keys = this._selector.selectedKeys();
                this._load = keys.size();
                it = this._selector.selectedKeys().iterator();

                // loop over all selected channels, just take care of thread
                // interruption
                while ( it.hasNext() && !isInterrupted() )
                {
                    selKey = (SelectionKey) it.next();
                    // remove the SelectionKey from the Iterator otherwise it
                    // will be lost
                    it.remove();

                    try
                    {
                        // validate the key
                        if ( !selKey.isValid() ) continue;

                        // at least our ConnectionAcceptor has created a client
                        // ConnectionHeader
                        clientInfo = (ConnectionHeader) selKey.attachment();

                        // first check read-availbility
                        if ( selKey.isReadable() )
                        {
                            // get the underlying socket channel
                            cChannel = (SocketChannel) selKey.channel();
                            // cancel the channels registration with our
                            // Selector
                            selKey.cancel();

                            // little bit paranoia
                            if ( cChannel != null && cChannel.isOpen() )
                            {
                                // don't we support NIO?
                                if ( !this._serverInfo.hasNonBlockingReadWrite() )
                                {
                                    logger.log( Level.FINEST,
                                                "Setting socket to blocking mode for further io operations..." );

                                    // prepare the channel for upcoming blocking
                                    // network operations
                                    cChannel.configureBlocking( true );
                                }

                                // schedule a asynchronious read-process operation
                                this._readpool.invokeLater( new ConnectionReader( this, this._serverInfo, clientInfo ) );
                            }
                        }
                        else if ( selKey.isWritable() )
                        {
                            // get the underlying socket channel
                            cChannel = (SocketChannel) selKey.channel();
                            // cancel the channels registration with our
                            // Selector
                            selKey.cancel();

                            // little bit paranoia
                            if ( cChannel != null && cChannel.isOpen() )
                            {
                                // don't we support NIO?
View Full Code Here

Examples of java.nio.channels.SelectionKey

            // clean out cancelled key list
            this._selector.selectNow();
            Object[] arr = null;
            ConnectionHeader header = null;
            SocketChannel channel = null;
            SelectionKey sk = null;

            for ( ; count < size; count++ )
            {
                arr = (Object[]) this._aspirants.remove( 0 );
                header = (ConnectionHeader) arr[0];
                channel = header.getChannel();
                // set a previously blocking socket channel to non-blocking
                // mode to allow selector operations on it
                if ( channel.isBlocking() )
                {
                    logger.log( Level.FINEST,
                                "Setting socket temporarily to non-blocking until further connection processing..." );
                    channel.configureBlocking( false );
                }

                sk = channel.keyFor( this._selector );
                if ( sk == null )
                {
                    // register with no interest
                    sk = channel.register( this._selector, 0 );
                }

                // attach the client connection header
                sk.attach( header );
                // now set the requested interest
                sk.interestOps( ((Integer) arr[1]).intValue() );
            }
        }

        if ( logger.isLoggable( Level.FINEST ) )
        {
View Full Code Here

Examples of java.nio.channels.SelectionKey

        //TODO:记录下异常
        e.printStackTrace();
      }
       
        for(Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) {
          SelectionKey sk = i.next();
          i.remove();
         
          if(sk.isValid() == false) {
            //TODO:考虑是否抛出异常
          }
         
          if(sk.isAcceptable()) {
           
            SocketChannel sc = null;
            try {
            sc = this.ssChannel.accept();
            sc.configureBlocking(false);
View Full Code Here

Examples of java.nio.channels.SelectionKey

   
    channel.configureBlocking(false);                //设置为非阻塞
   
    if(session.getClass() == IoSessionImpl.class) {
      //注册
      SelectionKey selectKey = channel.register(selector, SelectionKey.OP_READ, session)//向选择器注册通道

      session.setSelectionKey(selectKey);   //设置会话的选择键

      //session.setOwnerDispatcher(this);    //设置归属IO处理器

      this.onRegisterSession(session);
    }
   
    else if(session.getClass() == ClientIoSession.class) {  //注册连接操作
      ClientIoSession clientIoSession = (ClientIoSession) session;
      SelectionKey selectKey = channel.register(selector, SelectionKey.OP_CONNECT, session);
      channel.connect(clientIoSession.getConnectAddress());
      session.setSelectionKey(selectKey);
    }
   
    //开启定时检查
View Full Code Here

Examples of java.nio.channels.SelectionKey

        //TODO:记录异常
        e.printStackTrace();
      }

      for(Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) {
        SelectionKey sk = i.next();
        i.remove();

       
        IoSessionImpl session = (IoSessionImpl) sk.attachment();
       
        if(sk.isValid() == false) {
          try {
            session.closeNow0();
          } catch (IOException e) {}
          continue;
        }

       
        if(sk.isValid() && sk.isConnectable()) {
          //TODO:
          try {
            handleConnect(session);
          } catch (IOException e) {
            //TODO:记录下异常
            e.printStackTrace();
            ConnectFuture future =  (ConnectFuture) ((ClientIoSession) session).getConnectFuture();
            future.setComplete(e);          //设置完成
            session.close();
          }
        }
       
        if(sk.isValid() && sk.isReadable()) {
          handleRead(session);
        }

        if(sk.isValid() && sk.isWritable()) {
          handleWrite(session);
        }
       
       
      }
View Full Code Here

Examples of java.nio.channels.SelectionKey

            Iterator it = keys.iterator();
            while (it.hasNext())
            {
                // Get a key representing one of bits of I/O
                // activity
                SelectionKey key = (SelectionKey)it.next();
               
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ)
                {
                    SocketChannel ch = (SocketChannel)key.channel();
                    java.net.Socket ss = (java.net.Socket)ch.socket();
                    Socket s = (Socket)key.attachment();
                    if (s != null)
                    {
//                        System.out.println(s + ": OnRead");
                        s.OnRead();
                        if (s.LineProtocol())
                        {
                            s.ReadLine(); // eat ibuf to m_line, calls OnLine
                        }
                    }
                }
                if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE)
                {
                    SocketChannel ch = (SocketChannel)key.channel();
                    java.net.Socket ss = (java.net.Socket)ch.socket();
                    Socket s = (Socket)key.attachment();
                    if (s != null)
                    {
//                        System.out.println(s + ": OnWrite");
                        s.OnWrite();
                    }
                }
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
                {
                    ServerSocketChannel ch = (ServerSocketChannel)key.channel();
                    java.net.ServerSocket ss = (java.net.ServerSocket)ch.socket();
                    Socket s = (Socket)key.attachment();
                    if (s != null)
                    {
//                        System.out.println(s + ": OnRead(ACCEPT)");
                        s.OnRead(); // ListenSocket.OnRead will call OnAccept on new Socket
                    }
                }
                if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT)
                {
                    SocketChannel ch = (SocketChannel)key.channel();
                    java.net.Socket ss = (java.net.Socket)ch.socket();
                    Socket s = (Socket)key.attachment();
                    if (s != null)
                    {
//                        System.out.println(s + ": OnConnect");
                        ch.finishConnect();
                        s.SetConnecting(false);
                        s.GetKey().interestOps(SelectionKey.OP_READ);
                        s.OnConnect();
                    }
                }
               
            } // while
            keys.clear();
           
            // deregister
            it = m_selector.keys().iterator();
            boolean bRemoved = false;
            while (it.hasNext())
            {
                // Get a key representing one of bits of I/O
                // activity
                SelectionKey key = (SelectionKey)it.next();
                Socket p = (Socket)key.attachment();
                if (p.CloseAndDelete())
                {
                    p.OnDelete(); // OnDelete closes Channel
                    key.cancel();
                    m_sockets.remove(p); // no longer Valid
                    bRemoved = true;
                }
            } // while - check for delete
            if (bRemoved)
View Full Code Here

Examples of java.nio.channels.SelectionKey

    public void Add(Socket x)
    {
        SelectableChannel ch = x.GetChannel();
        try
        {
            SelectionKey key = ch.register( m_selector, ch.validOps(), x);
            x.SetKey(key);
            x.OnInitialOps();
            m_sockets.add(x);
            PrintSockets();
        } catch (Exception e)
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.