Example usage for java.nio.channels ServerSocketChannel open

List of usage examples for java.nio.channels ServerSocketChannel open

Introduction

In this page you can find the example usage for java.nio.channels ServerSocketChannel open.

Prototype

public static ServerSocketChannel open() throws IOException 

Source Link

Document

Opens a server-socket channel.

Usage

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

public IncomingConnectionThread(ByteBufferedChannelManager byteBufferedChannelManager,
        boolean isListeningThread, InetSocketAddress listeningAddress) throws IOException {
    super("Incoming Connection Thread");

    this.selector = Selector.open();
    this.byteBufferedChannelManager = byteBufferedChannelManager;

    if (isListeningThread) {
        this.listeningSocket = ServerSocketChannel.open();
        this.listeningSocket.configureBlocking(false);
        listeningSocket.register(this.selector, SelectionKey.OP_ACCEPT);
        this.listeningSocket.socket().bind(listeningAddress);
        LOG.debug("Listening on " + this.listeningSocket.socket().getLocalSocketAddress());
    } else {/*from ww w.j  a  v a 2  s. c  o  m*/
        this.listeningSocket = null;
    }
}

From source file:org.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java

/**
 * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
 * there. Then binds the obtained socket.
 * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
 * IPv6 address. Works on Oracle JDK 1.7.
 *//*w ww  .jav a2s . c o  m*/
private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
    while (true) {
        int port = HBaseTestingUtility.randomFreePort();
        InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
        ServerSocketChannel channel = null;
        ServerSocket serverSocket = null;
        try {
            channel = ServerSocketChannel.open();
            serverSocket = channel.socket();
            serverSocket.bind(addr); // This does not work
            break;
        } catch (BindException ex) {
            //continue
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (channel != null) {
                channel.close();
            }
        }
    }
}

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

@Override
public void run() {
    try {/*www  .  j av  a2s .  co  m*/
        Log.get().log(Level.INFO, "Server listening on port {0}", port);

        // Create a Selector that handles the SocketChannel multiplexing
        final Selector readSelector = Selector.open();
        final Selector writeSelector = Selector.open();

        // Start working threads
        final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors());
        ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
        for (int n = 0; n < workerThreads; n++) {
            cworkers[n] = new ConnectionWorker();
            cworkers[n].start();
        }
        Log.get().log(Level.INFO, "{0} worker threads started.", workerThreads);

        ChannelWriter.getInstance().setSelector(writeSelector);
        ChannelReader.getInstance().setSelector(readSelector);
        ChannelWriter.getInstance().start();
        ChannelReader.getInstance().start();

        final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(true); // Set to blocking mode

        // Configure ServerSocket; bind to socket...
        serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(this.port));

        while (isRunning()) {
            SocketChannel socketChannel;

            try {
                // As we set the server socket channel to blocking mode the
                // accept()
                // method will block.
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                assert socketChannel.isConnected();
                assert socketChannel.finishConnect();
            } catch (IOException ex) {
                // Under heavy load an IOException "Too many open files may
                // be thrown. It most cases we should slow down the
                // connection accepting, to give the worker threads some
                // time to process work.
                Log.get().log(Level.SEVERE, "IOException while accepting connection: {0}", ex.getMessage());
                Log.get().info("Connection accepting sleeping for seconds...");
                Thread.sleep(5000); // 5 seconds
                continue;
            }

            //FIXME conn should be NNTPConnection
            final SynchronousNNTPConnection conn = (SynchronousNNTPConnection) context
                    .getBean("syncNNTPConnection", NNTPConnection.class);
            conn.setChannelWrapper(new SocketChannelWrapperFactory(socketChannel).create());
            Connections.getInstance().add(conn);

            try {
                SelectionKey selKeyWrite = registerSelector(writeSelector, socketChannel,
                        SelectionKey.OP_WRITE);
                registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);

                Log.get().log(Level.INFO, "Connected: {0}", socketChannel.socket().getRemoteSocketAddress());

                // Set write selection key and send hello to client
                conn.setWriteSelectionKey(selKeyWrite);
                conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost") + " <unknown version>" // + Application.VERSION
                        + " news server ready - (posting ok).");
            } catch (CancelledKeyException cke) {
                Log.get().log(Level.WARNING, "CancelledKeyException {0} was thrown: {1}",
                        new Object[] { cke.getMessage(), socketChannel.socket() });
            } catch (ClosedChannelException cce) {
                Log.get().log(Level.WARNING, "ClosedChannelException {0} was thrown: {1}",
                        new Object[] { cce.getMessage(), socketChannel.socket() });
            }
        }
    } catch (BindException ex) {
        // Could not bind to socket; this is a fatal, so perform a shutdown
        Log.get().log(Level.SEVERE, ex.getLocalizedMessage() + " -> shutdown sonews", ex);
        setRunning(false);
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:xbird.server.services.RemotePagingService.java

private static ServerSocketChannel createServerSocketChannel() {
    try {/*from   w  ww .j  a  v  a 2s  . c o m*/
        return ServerSocketChannel.open();
    } catch (IOException e) {
        throw new IllegalStateException("failed to create a server socket", e);
    }
}

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

@Override
public boolean init() {
    try {/*  www .  ja  va2 s  .  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: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);// w w  w. j  a  va2 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:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void canAcceptSocketConnections() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/*from www .  j  a  v a  2 s.  co m*/
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

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();/*from w  w  w  . j  av  a 2 s . c  o m*/

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

    // Start thread
    start();
}

From source file:voldemort.server.niosocket.NioSocketService.java

public NioSocketService(RequestHandlerFactory requestHandlerFactory, int port, int socketBufferSize,
        boolean socketKeepAlive, int selectors, String serviceName, boolean enableJmx, int acceptorBacklog,
        long selectorMaxHeartBeatTimeMs) {

    super(ServiceType.SOCKET, port, serviceName, enableJmx);
    this.requestHandlerFactory = requestHandlerFactory;
    this.socketBufferSize = socketBufferSize;
    this.socketKeepAlive = socketKeepAlive;
    this.acceptorBacklog = acceptorBacklog;
    this.selectorMaxHeartBeatTimeMs = selectorMaxHeartBeatTimeMs;

    try {//from  w w  w  .j a va 2 s  . com
        this.serverSocketChannel = ServerSocketChannel.open();
    } catch (IOException e) {
        throw new VoldemortException(e);
    }

    this.endpoint = new InetSocketAddress(port);

    this.selectorManagers = new NioSelectorManager[selectors];

    String threadFactoryPrefix = "voldemort-" + serviceName;
    this.selectorManagerThreadPool = Executors.newFixedThreadPool(selectorManagers.length,
            new DaemonThreadFactory(threadFactoryPrefix));
    this.statusManager = new StatusManager((ThreadPoolExecutor) this.selectorManagerThreadPool);
    this.acceptorThread = new Thread(new Acceptor(), threadFactoryPrefix + ".Acceptor");
}

From source file:jp.queuelinker.system.net.SelectorThread.java

public int openServerSocket(final InetSocketAddress bindAddress, final SelectorCallBack callBack)
        throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    serverChannel.socket().setReuseAddress(true);
    serverChannel.socket().bind(bindAddress);
    return addSocketChannel(serverChannel, callBack);
}