Example usage for java.nio.channels SocketChannel register

List of usage examples for java.nio.channels SocketChannel register

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel register.

Prototype

public final SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException 

Source Link

Document

Registers this channel with the given selector, returning a selection key.

Usage

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleAccept(final ServerSocketChannel serverChannel, final Selector selector)
        throws IOException {
    final SocketChannel channel = serverChannel.accept();
    if (channel == null) {
        return;// w ww . jav a  2  s  .  c o m
    }
    channel.configureBlocking(false);
    channel.register(selector, SelectionKey.OP_READ, new GridMessageBuffer());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Accepted a new client connection: " + channel.socket().getRemoteSocketAddress());
    }
}

From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java

public static SelectionKey registerSelector(final Selector selector, final SocketChannel channel, final int op)
        throws CancelledKeyException, ClosedChannelException {
    // Register the selector at the channel, so that it will be notified
    // on the socket's events
    synchronized (RegisterGate) {
        // Wakeup the currently blocking reader/writer thread; we have
        // locked the RegisterGate to prevent the awakened thread to block again
        selector.wakeup();/*from  w ww  .  j  av a  2s  .  c  o m*/

        // Lock the selector to prevent the waiting worker threads going
        // into selector.select() which would block the selector.
        synchronized (selector) {
            return channel.register(selector, op, null);
        }
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private SocketInfo initConnections(Selector selector) throws IOException {
    log.trace("initConnections()");

    for (URI target : addresses) {
        SocketChannel channel = SocketChannel.open();
        channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
        channel.configureBlocking(false);
        try {/*from  ww w. j av  a2  s  . co  m*/
            channel.register(selector, SelectionKey.OP_CONNECT, target);

            if (channel.connect(new InetSocketAddress(target.getHost(), target.getPort()))) { // connected immediately
                channel.configureBlocking(true);
                return new SocketInfo(target, channel.socket());
            }
        } catch (Exception e) {
            closeQuietly(channel);
            log.trace("Error connecting to '{}': {}", target, e);
        }
    }

    return null;
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

/**
 * ?, ?Session, ?Session, // ww w. jav a 2 s  . c  om
 * Session?
 * @param key
 * @throws IOException
 */
private void onAccept(SelectionKey key) throws IOException {
    SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
    opsChangeRequstMap.put(channel, new SocketChannelOPSChangeRequest(channel, 0));
    if (logger.isWarnEnabled())
        logger.warn("Accept client from : " + channel.socket().getRemoteSocketAddress());
    channel.configureBlocking(false);
    Session session = sessionManager.newSession(this, channel, false);
    channel.register(selector, SelectionKey.OP_READ, session);
    session.start();
}

From source file:com.springrts.springls.Clients.java

/**
 * Will create new <code>Client</code> object, add it to the 'clients' list
 * and register its socket channel with 'readSelector'.
 * @param sendBufferSize specifies the sockets send buffer size.
 *///from  w w w. j  av  a 2  s .co  m
public Client addNewClient(SocketChannel chan, Selector readSelector, int sendBufferSize) {
    Client client = new Client(chan);
    client.receiveContext(context);
    clients.add(client);

    // register the channel with the selector
    // store a new Client as the Key's attachment
    try {
        chan.configureBlocking(false);
        chan.socket().setSendBufferSize(sendBufferSize);
        // TODO this doesn't seem to have an effect with java.nio
        //chan.socket().setSoTimeout(TIMEOUT_LENGTH);
        client.setSelKey(chan.register(readSelector, SelectionKey.OP_READ, client));
    } catch (IOException ioex) {
        LOG.warn("Failed to establish a connection with a client", ioex);
        killClient(client, "Failed to establish a connection");
        return null;
    }

    return client;
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {//from w w  w.  j a v  a 2 s  .  com
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Accept an icoming connection/*from   w w w  .ja va  2 s  . c om*/
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}

From source file:com.app.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*from   w w w  .  jav  a 2s.  co m*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //log.info("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:com.web.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*from  ww  w.  ja  v  a2 s  .  c  o m*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //System.out.println(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //System.out.println(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //System.out.println("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //System.out.println("In read obect");
                                    object = ois.readObject();
                                    //System.out.println("Class Cast");
                                    //System.out.println("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //System.out.println("readObject");
                                    //System.out.println("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //System.out.println("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //System.out.println(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //System.out.println(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap
                                                .get(earServicesDirectory + "/" + serviceRegistry[0] + "/"
                                                        + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(jarservicesDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // System.out.println("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // System.out.println("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * System.out.println(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //System.out.println("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //System.out.println("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //System.out.println(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //System.out.println("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //System.out.println(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //System.out.println("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //System.out.println("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;

                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket("0.0.0.0",
                                            Integer.parseInt(nodesport[random.nextInt(nodesport.length)]));
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //System.out.println("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   System.out.println("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //System.out.println("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //System.out.println("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //System.out.println(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //System.out.println("In write1");
                                numberOfServicesRequests++;
                                //System.out.println("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {

                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
}

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Attempts to accept incoming new connections.
 * /* w  ww  .  j a  v  a2  s .  c  o m*/
 * @return
 *       True if there was no error, false if an error occured.
 */
private boolean acceptConnections() {
    SocketChannel socketChannel = null;

    // Only bother if the connection is open.
    if (serverSocketChannel.isOpen()) {

        // Attempt to get a connection.
        try {
            socketChannel = serverSocketChannel.accept();
        } catch (Exception e) {
            log.error("Unexpected IO exception when accepting a connection.", e);
            return false;
        }

        // If there was a client connecting, take care of them.
        // Make sure to attach a new ClientInfo that we will fill out later upon validation.
        if (socketChannel != null) {
            try {
                log.info("Incoming new client connection from {}.",
                        socketChannel.getRemoteAddress().toString());
                ClientInfo clientInfo = new ClientInfo(socketChannel.getRemoteAddress().toString());
                socketChannel.configureBlocking(false);
                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.register(selector, SelectionKey.OP_READ, clientInfo);
                clientInfo.markMessageReceived(); // Prevent timing out from a connection.

                //               // TEST
                //               int amount = 1024 * 16;
                //               byte[] hi = new byte[amount];
                //               for (int i = 0; i < amount; i++)
                //                  hi[i] = (byte)(Math.random() * 255);
                //               ByteBuffer bb = ByteBuffer.allocate(amount);
                //               bb.put(hi);
                //               bb.flip();
                //               
                //               int wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("Server wrote: " + wrote + " bytes to a client");
                //               }
                //               
                //               Thread.sleep(4000);
                //               
                //               bb = ByteBuffer.allocate(5);
                //               bb.put(new byte[] { 1, 2, 3, 4, 5 });
                //               bb.flip();
                //               wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("2) Server wrote: " + wrote + " bytes to a client");
                //               }

                // TODO - send global version of the file.
            } catch (ClosedChannelException e) {
                log.error("Channel closed exception when registering a connected client.", e);
                return false;
            } catch (IOException e) {
                log.error("IO exception when registering a new client connection.", e);
                return false;
            } catch (Exception e) {
                log.error("Unexpected exception when registering a new client connection.", e);
                return false;
            }
        }
    }

    // Signal all is good.
    return true;
}