Package java.nio.channels

Examples of java.nio.channels.SocketChannel


    /**
     * Gets a channel to communicate with the server.
     * @return a socket channel.
     */
    private SocketChannel getChannel() {
        SocketChannel channel = null;

        // open
        try {
            channel = SocketChannel.open();
        } catch (IOException e) {
            cleanChannel(channel);
            throw new IllegalStateException("Cannot open a channel", e);
        }

        // Connect
        try {
            channel.connect(this.socketAddress);
        } catch (IOException e) {
            cleanChannel(channel);
            throw new IllegalStateException("Cannot connect the channel", e);
        }

View Full Code Here


        Class<?> clazz = null;

        try {
            return super.findClass(name);
        } catch (ClassNotFoundException cnfe) {
            SocketChannel channel = null;
            try {
                long tStart = System.currentTimeMillis();
                // Get channel
                channel = getChannel();
                ByteBuffer answerBuffer = sendRequest(new ClassRequest(name), channel);
View Full Code Here

     * Ask and return the remote PROVIDER_URL in order to connect with RMI.
     * @return a string with the PROVIDER_URL value.
     */
    public String getProviderURL() {
        String providerURL = null;
        SocketChannel channel = null;
        try {
            long tStart = System.currentTimeMillis();
            // Get channel
            channel = getChannel();
            ByteBuffer answerBuffer = sendRequest(new ProviderURLRequest(), channel);
View Full Code Here

        if (name.startsWith("META-INF")) {
            return null;
        }

        SocketChannel channel = null;
        try {
            long tStart = System.currentTimeMillis();

            // Get channel
            channel = getChannel();
View Full Code Here

     * Handle a new client that is being connected.
     * @throws IOException if cannot accept the client
     */
    private void handleAccept() throws IOException {
        // new incoming connection
        SocketChannel client = this.server.accept();

        // Non blocking client
        client.configureBlocking(false);

        // Register client (with an empty channel attachment)
        client.register(this.selector, SelectionKey.OP_READ, new ChannelAttachment());
    }
View Full Code Here

     * @param selectionKey the selected key.
     * @throws IOException if cannot read from the channel.
     */
    private void handleRead(final SelectionKey selectionKey) throws IOException {
        // Get the client channel that has data to read
        SocketChannel client = (SocketChannel) selectionKey.channel();

        // current bytecode read
        ChannelAttachment channAttachment = (ChannelAttachment) selectionKey.attachment();
        ByteBuffer channBuffer = channAttachment.getByteBuffer();

        // Read again
        int bytesread = client.read(channBuffer);
        if (bytesread == -1) {
            // close (as the client has been disconnected)
            selectionKey.cancel();
            client.close();
        }

        // Client send data, analyze data

        // Got header ?
        if (channBuffer.position() >= Message.HEADER_SIZE) {

            // Yes, got header
            // Check if it is a protocol that we manage
            byte version = channBuffer.get(0);
            if (version != PROTOCOL_VERSION) {
                selectionKey.cancel();
                client.close();
                throw new IllegalStateException("Invalid protocol version : waiting '" + PROTOCOL_VERSION + "', got '" + version
                        + "'.");
            }

            // Get operation asked by client
            byte opCode = channBuffer.get(1);

            // Length
            int length = channBuffer.getInt(2);
            if (length < 0) {
                selectionKey.cancel();
                client.close();
                throw new IllegalStateException("Invalid length for client '" + length + "'.");
            }

            if (length > MAX_LENGTH_INCOMING_MSG) {
                selectionKey.cancel();
                client.close();
                throw new IllegalStateException("Length too big, max length = '" + MAX_LENGTH_INCOMING_MSG + "', current = '"
                        + length + "'.");
            }

            // Correct header and correct length ?
            if (channBuffer.position() >= Message.HEADER_SIZE + length) {
                // set the limit (specified in the length), else we have a
                // default buffer limit
                channBuffer.limit(Message.HEADER_SIZE + length);

                // duplicate this buffer
                ByteBuffer dataBuffer = channBuffer.duplicate();

                // skip header (already analyzed)
                dataBuffer.position(Message.HEADER_SIZE);

                // Switch on operations :
                try {
                    switch (opCode) {
                    case ProtocolConstants.CLASS_REQUEST:
                        handleReadClassRequest(selectionKey, dataBuffer);
                        break;
                    case ProtocolConstants.RESOURCE_REQUEST:
                        handleReadResourceRequest(selectionKey, dataBuffer);
                        break;
                    case ProtocolConstants.PROVIDER_URL_REQUEST:
                        handleReadProviderURLRequest(selectionKey, dataBuffer);
                        break;
                    default:
                        // nothing to do
                    }
                } catch (Exception e) {
                    // clean
                    selectionKey.cancel();
                    client.close();
                    throw new IllegalStateException("Cannot handle request with opCode '" + opCode + "'.", e);
                }
            }
        }

View Full Code Here

     * Handle all write operations on channels.
     * @param selectionKey the selected key.
     * @throws IOException if cannot write to the channel.
     */
    private void handleWrite(final SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();

        // Write the data that was attached on the selection key
        ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
        if (buffer.hasRemaining()) {
            channel.write(buffer);
        } else {
            // finished to write, close
            channel.close();
        }
    }
View Full Code Here

                    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
                            if ( cChannel != null )
                            {
                                // little bit tuning
                                cChannel.socket().setTrafficClass( EJConstants.IPTOS_THROUGHPUT );
                                cChannel.socket().setReuseAddress( true );
                                cChannel.socket().setSoLinger( false, 0 );
                               
                                // ensure that the socket channel is prepared
                                // for non-blocking operations
                                cChannel.configureBlocking( false );
                                // create a new ConnectionHeader for all
                                // upcoming operations on the
                                // accepted socket connection
                                header = new ConnectionHeader( cChannel, cChannel.socket().getRemoteSocketAddress()
                                        .toString(), true );
                                // register the channel on another thread which
                                // will do further connection handling
                                getProcessor().register( header, SelectionKey.OP_READ );

                                if ( logger.isLoggable( Level.FINE ) )
                                {
                                    logger.log( Level.FINE, "Connection accepted from "
                                            + cChannel.socket().getRemoteSocketAddress() );
                                }
                            }
                        }
                    }
                    catch ( CancelledKeyException cke )
View Full Code Here

     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        Object request = null;
        SocketChannel channel = this._senderInfo.getChannel();

        try
        {
            if ( !this._senderInfo.isConnected() )
            {
                log.log( Level.FINEST, "Handshaking client..." );
                // handshake the client, get infos about compression...
                this._senderInfo = DataChannel.getInstance().handshake( this._receiverInfo, channel,
                                                                        EJConstants.EJOE_CONNECTION_TIMEOUT );
            }

            if ( this._senderInfo != null )
            {
                log.log( Level.FINEST, "Remote requested " + this._senderInfo.getAdapterName() );

                SerializeAdapter adapter = AdapterFactory.createAdapter( this._senderInfo.getAdapterName() );

                if ( this._receiverInfo.hasNonBlockingReadWrite() )
                {
                    log.log( Level.FINEST, "Going to read client request on a non blocking socket..." );
                    request = read( adapter );
                }
                else
                {
                    log.log( Level.FINEST, "Going to read client request on a blocking socket..." );
                    request = readBlocked( adapter );
                }

                this._senderInfo.releaseAttachment();
                this._senderInfo.releaseWaitingBuffer();

                log.log( Level.FINE, "Client request read." );

                Object result = handleObject( request );

                if ( this._registrar.isValid() )
                {
                    this._senderInfo.setAttachment( result );
                    this._registrar.register( this._senderInfo, SelectionKey.OP_WRITE );
                }
            }
            else
            {
                log.log( Level.WARNING, "Connection timeout reached while waiting for Handshake complete. "
                        + "Closing connection." );
                shutdownConnection( channel );
            }
        }
        // partial read detected, registering for read again
        catch ( IncompleteIOException ioe )
        {
            this._senderInfo.setWaitingBuffer( ioe.getIOBuffer() );
            this._registrar.register( this._senderInfo, SelectionKey.OP_READ );
        }
        catch ( EOFException eof )
        {
            log.log( Level.FINEST, "EOF received while reading client data " + "- closing connection." );
            shutdownConnection( channel );
        }
        catch ( ParseException pe )
        {
            log.log( Level.WARNING, "Unparseable connection header detected!", pe );
            if ( !this._senderInfo.isHttp() )
            {
                this._senderInfo.setAttachment( new RemoteException( "Unparseable connection header!", pe ) );
            }
            else
            {
                this._senderInfo.setAttachment( new RemoteException( "Unparseable connection header!", pe ),
                                                HttpResponse.HTTP_BAD_REQUEST );
            }

            this._registrar.register( this._senderInfo, SelectionKey.OP_WRITE );
        }
        catch ( SocketTimeoutException ste )
        {
            log.log( Level.FINE, "Timeout occured while waiting for client data!", ste );
            shutdownConnection( channel );
        }
        catch ( RemoteException re )
        {
            if ( !this._senderInfo.isHttp() )
            {
                this._senderInfo.setAttachment( re );
            }
            else
            {
                this._senderInfo.setAttachment( re, HttpResponse.HTTP_INTERNAL_SERVER_ERROR );
            }
            this._registrar.register( this._senderInfo, SelectionKey.OP_WRITE );
        }
        // the client did something strange with the channel, probably the
        // client is just too slow for
        catch ( NonReadableChannelException e )
        {
            log.log( Level.INFO, "Connection probably closed by client." );
            shutdownConnection( channel );
        }
        // the client did close the connection, or the connection was
        // disconnected
        catch ( ClosedChannelException cce )
        {
            log.log( Level.INFO, "Connection closed by client." );
            shutdownConnection( channel );
        }
        catch ( Throwable e )
        {
            if ( !channel.isBlocking() && channel.isConnected() && channel.isOpen() )
            {
                // something goes completely wrong!
                log.log( Level.WARNING, "!!! Exception while reading client data !!! "
                        + "Probably the client just closed the connection but it could also be a serious failure.", e );
            }
View Full Code Here

        }

        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?
                                if ( !this._serverInfo.hasNonBlockingReadWrite() )
                                {
                                    if ( !clientInfo.hasAttachment() ) continue;
                                    // prepare the channel for upcoming blocking
                                    // network operations
                                    cChannel.configureBlocking( true );
                                }

                                // schedule a asynchronious socket-write
                                // operation
                                this._writePool
View Full Code Here

TOP

Related Classes of java.nio.channels.SocketChannel

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.