Example usage for java.nio.channels SelectionKey OP_ACCEPT

List of usage examples for java.nio.channels SelectionKey OP_ACCEPT

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey OP_ACCEPT.

Prototype

int OP_ACCEPT

To view the source code for java.nio.channels SelectionKey OP_ACCEPT.

Click Source Link

Document

Operation-set bit for socket-accept operations.

Usage

From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java

protected void __doRegisterEvent() throws IOException {
    if (isServer()) {
        processor().registerEvent(__channel, SelectionKey.OP_ACCEPT, null);
    } else {/*from  w ww  . jav  a 2 s  .com*/
        processor().registerEvent(__channel, SelectionKey.OP_CONNECT, session());
        if (connectionTimeout() > 0) {
            session().connectSync(connectionTimeout());
        }
    }
}

From source file:com.taobao.gecko.core.nio.impl.SelectorManager.java

/**
 * channel/*w  w  w  .  ja  va  2 s .c  o  m*/
 * 
 * @param channel
 * @param ops
 * @param attachment
 * @return
 */
public final Reactor registerChannel(final SelectableChannel channel, final int ops, final Object attachment) {
    this.awaitReady();
    int index = 0;
    // AcceptReactor
    if (ops == SelectionKey.OP_ACCEPT || ops == SelectionKey.OP_CONNECT) {
        index = 0;
    } else {
        if (this.dividend > 0) {
            index = this.sets.incrementAndGet() % this.dividend + 1;
        } else {
            index = 0;
        }
    }
    final Reactor reactor = this.reactorSet[index];
    reactor.registerChannel(channel, ops, attachment);
    return reactor;

}

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

@Override
public boolean init() {
    try {//from   w w  w.j  a  va2s. c  o  m
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket()
                .bind(hostName == null ? new InetSocketAddress(port) : new InetSocketAddress(hostName, port));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // ??
        // ?, socket?
        //readerExecutor = Executors.newFixedThreadPool(1, new WaveriderThreadFactory(NET_WORK_READER, null, true));
        //writerExecutor = Executors.newFixedThreadPool(1, new WaveriderThreadFactory(NET_WORK_WRITER, null, true));

        // ?
        netWorkServerThread = new Thread(this, NET_WORK_SERVER_THREAD_NAME);
        netWorkServerThread.setDaemon(true);
    } catch (IOException e) {
        logger.error("Init DefaultNetworkServer failed: ", e);
        throw new RuntimeException(e);
    }

    return true;
}

From source file:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {/*from  w w  w  .j a v  a2  s .  c o  m*/
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}

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

private static void startListening(final Selector connectSelector, final int port) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    ServerSocket servSocket = serverChannel.socket();
    servSocket.setReuseAddress(true);//  ww w .  ja v  a 2 s.  c o m
    servSocket.bind(new InetSocketAddress(port));

    serverChannel.register(connectSelector, SelectionKey.OP_ACCEPT);
    if (LOG.isInfoEnabled()) {
        LOG.info("GridNioServer is started at port: " + port);
    }
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private static String describeInterestOps(int interestOps) {
    final TreeSet<String> result = new TreeSet<String>();
    if ((interestOps & SelectionKey.OP_ACCEPT) != 0)
        result.add("ACCEPT");
    if ((interestOps & SelectionKey.OP_CONNECT) != 0)
        result.add("CONNECT");
    if ((interestOps & SelectionKey.OP_READ) != 0)
        result.add("READ");
    if ((interestOps & SelectionKey.OP_WRITE) != 0)
        result.add("WRITE");
    return StringUtils.join(result, "|");
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

LDAPListener(ContactLoader loader, FilterMask[] hosts, FilterMask[] addresses, int port) throws Exception {

    // Starting server
    log.info("LDAP server starting on port " + port + "...");

    // Store pointers
    this.loader = loader;
    this.hosts = hosts;
    this.addresses = addresses;

    // Allocate an unbound server socket channel
    serverChannel = ServerSocketChannel.open();

    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();

    // Set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(port));

    // Set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);

    // Create a new Selector for use below
    selector = Selector.open();//  w  ww. ja v a2  s  .  com

    // Register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);

    // Start thread
    start();
}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** register a socket for ACCEPT events */
public void registerForAccept(NIOServerSocket theSocket) throws IOException {
    registerSocket(theSocket, SelectionKey.OP_ACCEPT);
}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//ww  w.  j a v  a 2 s . c  o m

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java

public void listen() throws Exception {
    doListen = true;/*from  www.jav  a 2 s  . c o m*/
    // allocate an unbound server socket channel
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    Selector selector = Selector.open();
    // set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(bind, port));
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (doListen) {
        // this may block for a long time, upon return the
        // selected set contains keys of the ready channels
        try {

            //System.out.println("Selecting with timeout="+timeout);
            int n = selector.select(timeout);
            //System.out.println("select returned="+n);
            if (n == 0) {
                continue; // nothing to do
            }
            // get an iterator over the set of selected keys
            Iterator it = selector.selectedKeys().iterator();
            // look at each key in the selected set
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                // Is a new connection coming in?
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    registerChannel(selector, channel, SelectionKey.OP_READ,
                            new ObjectReader(channel, selector, callback));
                }
                // is there data to read on this channel?
                //System.out.println("key readable="+key.isReadable());
                if (key.isReadable()) {
                    readDataFromSocket(key);
                } else {
                    //System.out.println("This shouldn't get called");
                    key.interestOps(key.interestOps() & (~key.OP_WRITE));
                }

                // remove key from selected set, it's been handled
                it.remove();
            }
            //System.out.println("Done with loop");
        } catch (java.nio.channels.CancelledKeyException nx) {
            log.warn("Replication client disconnected, error when polling key. Ignoring client.");
        } catch (Exception x) {
            log.error("Unable to process request in ReplicationListener", x);
        }

    } //while
    serverChannel.close();
    selector.close();
}