Java Code Examples for java.nio.channels.ServerSocketChannel#register()

The following examples show how to use java.nio.channels.ServerSocketChannel#register() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NIOServer.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
void startServer() throws IOException {
    // 准备好一个选择器, 监控是否有链接 (OP_ACCEPT)
    SelectorLoop connectionBell = new SelectorLoop();

    // 准备好一个选择器, 监控是否有read事件 (OP_READ)
    readBell = new SelectorLoop();

    // 开启一个server channel来监听
    ServerSocketChannel ssc = ServerSocketChannel.open();
    // 开启非阻塞模式
    ssc.configureBlocking(false);

    ServerSocket socket = ssc.socket();
    socket.bind(new InetSocketAddress("localhost", SOCKET_PORT));

    // 给选择器规定好要监听报告的事件, 这个选择器只监听新连接事件
    ssc.register(connectionBell.getSelector(), SelectionKey.OP_ACCEPT);
    new Thread(connectionBell).start();
}
 
Example 2
Source File: NioSocketDemo.java    From interview with MIT License 6 votes vote down vote up
public void initServer(int port) throws IOException {
    //通道
    ServerSocketChannel ssc = ServerSocketChannel.open();

    ssc.configureBlocking(false);//设置成非阻塞

    //绑定端口
    ssc.socket().bind(new InetSocketAddress(port));

    //获取到选择器
    selector = Selector.open();

    //注册到选择器上
    //监听用户的连接事件
    ssc.register(selector, SelectionKey.OP_ACCEPT);

    System.out.println("服务已经启动.......");
}
 
Example 3
Source File: ChannelListener.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 4
Source File: SocketChannelDispatcher.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;
    executor = Executors.newFixedThreadPool(maxConnections);

    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    if (maxBufferSize > 0) {
        serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to "
                    + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
 
Example 5
Source File: NIOServer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 1、创建选择器
    Selector selector = Selector.open();
    // 2、将通道注册到选择器上
    ServerSocketChannel ssChannel = ServerSocketChannel.open();
    // 设置非阻塞
    ssChannel.configureBlocking(false);
    ssChannel.register(selector, SelectionKey.OP_ACCEPT);
    // 3、监听事件
    ServerSocket serverSocket = ssChannel.socket();
    serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));

    while (true) {
        selector.select();
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keys.iterator();
        // 5、事件循环
        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            // 4、获取到达的事件
            if (key.isAcceptable()) {
                ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
                // 服务器会为每个新连接创建一个 SocketChannel
                SocketChannel socketChannel = ssChannel1.accept();
                socketChannel.configureBlocking(false);
                // 这个新连接主要用于从客户端读取数据
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                SocketChannel sChannel = (SocketChannel) key.channel();
                System.out.println(readDataFromSocketChannel(sChannel));
                sChannel.close();
            }
            keyIterator.remove();
        }

    }

}
 
Example 6
Source File: ConnectionListener.java    From tribaltrouble with GNU General Public License v2.0 5 votes vote down vote up
private final static SelectionKey createServerSocket(NetworkSelector network, InetAddress ip, int port) throws IOException {
	ServerSocketChannel server_channel = ServerSocketChannel.open();
	server_channel.configureBlocking(false);
	SocketAddress address = new InetSocketAddress(ip, port);
	server_channel.socket().setReuseAddress(true);
	server_channel.socket().bind(address);
	SelectionKey key = server_channel.register(network.getSelector(), SelectionKey.OP_ACCEPT);
	return key;
}
 
Example 7
Source File: NioSocketAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
    // Creates the listening ServerSocket
    ServerSocketChannel channel = ServerSocketChannel.open();

    boolean success = false;

    try {
        // This is a non blocking socket channel
        channel.configureBlocking(false);

        // Configure the server socket,
        ServerSocket socket = channel.socket();

        // Set the reuseAddress flag accordingly with the setting
        socket.setReuseAddress(isReuseAddress());

        // and bind.
        socket.bind(localAddress, getBacklog());

        // Register the channel within the selector for ACCEPT event
        channel.register(selector, SelectionKey.OP_ACCEPT);
        success = true;
    } finally {
        if (!success) {
            close(channel);
        }
    }
    return channel;
}
 
Example 8
Source File: EchoServer.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void startServer() throws Exception {
    selector = SelectorProvider.provider().openSelector();

    // Create non-blocking server socket.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    // Bind the server socket to localhost.
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), 8888);
    ssc.socket().bind(isa);

    // Register the socket for select events.
    SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);

    // Loop forever.
    for (;;) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator i = readyKeys.iterator();

        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            i.remove();

            if (sk.isAcceptable()) {
                doAccept(sk);
            }
            if (sk.isValid() && sk.isReadable()) {
                doRead(sk);
            }
            if (sk.isValid() && sk.isWritable()) {
                doWrite(sk);
            }
        }
    }
}
 
Example 9
Source File: GridNioServer.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates selector and binds server socket to a given address and port. If address is null
 * then will not bind any address and just creates a selector.
 *
 * @param addr Local address to listen on.
 * @return Created selector.
 * @throws IgniteCheckedException If selector could not be created or port is already in use.
 */
private Selector createSelector(@Nullable SocketAddress addr) throws IgniteCheckedException {
    Selector selector = null;

    ServerSocketChannel srvrCh = null;

    try {
        // Create a new selector
        selector = SelectorProvider.provider().openSelector();

        if (addr != null) {
            // Create a new non-blocking server socket channel
            srvrCh = ServerSocketChannel.open();

            srvrCh.configureBlocking(false);

            if (sockRcvBuf > 0)
                srvrCh.socket().setReceiveBufferSize(sockRcvBuf);

            // Bind the server socket to the specified address and port
            srvrCh.socket().bind(addr);

            // Register the server socket channel, indicating an interest in
            // accepting new connections
            srvrCh.register(selector, SelectionKey.OP_ACCEPT);
        }

        return selector;
    }
    catch (Throwable e) {
        U.close(srvrCh, log);
        U.close(selector, log);

        if (e instanceof Error)
            throw (Error)e;

        throw new IgniteCheckedException("Failed to initialize NIO selector.", e);
    }
}
 
Example 10
Source File: SelectorThread.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException
{
    ServerSocketChannel selectable = ServerSocketChannel.open();
    selectable.configureBlocking(false);

    ServerSocket ss = selectable.socket();
    
    if (address == null)
        ss.bind(new InetSocketAddress(tcpPort));
    else
        ss.bind(new InetSocketAddress(address, tcpPort));
    
    selectable.register(_selector, SelectionKey.OP_ACCEPT);
}
 
Example 11
Source File: Listener.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Add a listening port without creating a separate acceptor
 * thread.
 *
 * @param factory The connection factory for new connections
 *                on this port
 * @param port The port we are going to listen to.
 */
public synchronized void listenNoAcceptor(ConnectionFactory factory, int port)
    throws IOException {
    ServerSocketChannel s = ServerSocketChannel.open();

    s.configureBlocking(false);
    s.socket().setReuseAddress(true);
    s.socket().bind(new InetSocketAddress(port)); // use non-specific IP
    String host = s.socket().getInetAddress().getHostName();

    factories.put(s, factory);
    s.register(selector, SelectionKey.OP_ACCEPT);
    log.fine("listener " + host + ":" + port);
}
 
Example 12
Source File: TestMessageIO.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Waits for up to 1 second for the server to be acceptable */
private static void awaitAcceptable(ServerSocketChannel channel) throws IOException {
    Selector selector = Selector.open();
    SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
    try {
        assertEquals(true, awaitOp(selector, key, SelectionKey.OP_ACCEPT));
    } finally {
        // Cancel key and close selector
        key.cancel();
        selector.close();
    }
}
 
Example 13
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {
    Map.Entry           entry;
    Selector            selector;
    ServerSocketChannel sock_channel;
    MyInetSocketAddress key, value;

    if (remote !=null && local !=null)
        mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port));
    
    if (mapping_file !=null) {
        try {
            populateMappings(mapping_file);
        }
        catch (Exception ex) {
            log("Failed reading " + mapping_file);
            throw ex;
        }
    }

    log("\nProxy started at " + new java.util.Date());

    if (verbose) {
        log("\nMappings:\n---------");
        for (Iterator it=mappings.entrySet().iterator(); it.hasNext();) {
            entry=(Map.Entry) it.next();
            log(toString((InetSocketAddress) entry.getKey()) + " <--> "
                + toString((InetSocketAddress) entry.getValue()));
        }
        log("\n");
    }

    // 1. Create a Selector
    selector=Selector.open();

    // Create a thread pool (Executor)
    executor=new PooledExecutor(MAX_THREAD_POOL_SIZE);

    for (Iterator it=mappings.keySet().iterator(); it.hasNext();) {
        key=(MyInetSocketAddress) it.next();
        value=(MyInetSocketAddress) mappings.get(key);

        // if either source or destination are SSL, we cannot use JDK 1.4
        // NIO selectors, but have to fall back on separate threads per connection

        if (key.ssl() || value.ssl()) {
            // if(2 == 2) {
            SocketAcceptor acceptor=new SocketAcceptor(key, value);
            executor.execute(acceptor);
            continue;
        }

        // 2. Create a ServerSocketChannel
        sock_channel=ServerSocketChannel.open();
        sock_channel.configureBlocking(false);
        sock_channel.socket().bind(key);

        // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on
        //    select(). That way we can associate it with the mappings hashmap to find the corresponding
        //    value
        sock_channel.register(selector, SelectionKey.OP_ACCEPT, key);
    }

    // 4. Start main loop. won't return until CTRL-C'ed        
    loop(selector);
}
 
Example 14
Source File: MultiThreadNIOEchoServer.java    From cs-summary-reflection with Apache License 2.0 4 votes vote down vote up
private void startServer() throws Exception {
    selector = SelectorProvider.provider().openSelector();
    // 创建非阻塞的服务器Socket通道
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    // 绑定到指定的端口
    InetSocketAddress isa = new InetSocketAddress(8000);
    ssc.socket().bind(isa);
    // 注册到选择器,为监听,返回SelectionKey。无任何数据准备好则连接将阻塞
    ssc.register(selector, SelectionKey.OP_ACCEPT);

    // 轮询
    for (; ; ) {
        selector.select();
        Set<SelectionKey> readyKeys = selector.selectedKeys();
        Iterator<SelectionKey> i = readyKeys.iterator();
        long e = 0;
        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            // 连接操作处理
            if (sk.isAcceptable()) {
                doAccept(sk);
            }
            // 可读操作处理
            else if (sk.isValid() && sk.isReadable()) {
                if (!geym_time_stat.containsKey(((SocketChannel) sk.channel()).socket()))
                    geym_time_stat.put(
                            ((SocketChannel) sk.channel()).socket(),
                            System.currentTimeMillis());
                doRead(sk);
            }
            // 可写操作处理
            else if (sk.isValid() && sk.isWritable()) {
                doWrite(sk);
                e = System.currentTimeMillis();
                long b = geym_time_stat.remove(((SocketChannel) sk.channel()).socket());
                System.out.println("spend:" + (e - b) + "ms");
            }
            // 一定要取出这个SelectionKey,否则会重复处理相同的SelectionKey
            i.remove();
        }
    }
}
 
Example 15
Source File: Reactor.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务。
 */
public void start() {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(_port));
        _isRun = true;
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +_port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(selector, serverChannel));
        
        while (_isRun) {
            int selectNum = selector.select(_selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                     Acceptor acceptor = (Acceptor) selectionKey.attachment();
                     acceptor.accept();
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    Reader reader = (Reader) selectionKey.attachment();
                    reader.read();
                }
                
                // 移除已经处理过的Key
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}
 
Example 16
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 17
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 18
Source File: LotsOfCancels.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 19
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 20
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {
    Map.Entry           entry;
    Selector            selector;
    ServerSocketChannel sock_channel;
    MyInetSocketAddress key, value;

    if (remote !=null && local !=null)
        mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port));
    
    if (mapping_file !=null) {
        try {
            populateMappings(mapping_file);
        }
        catch (Exception ex) {
            log("Failed reading " + mapping_file);
            throw ex;
        }
    }

    log("\nProxy started at " + new java.util.Date());

    if (verbose) {
        log("\nMappings:\n---------");
        for (Iterator it=mappings.entrySet().iterator(); it.hasNext();) {
            entry=(Map.Entry) it.next();
            log(toString((InetSocketAddress) entry.getKey()) + " <--> "
                + toString((InetSocketAddress) entry.getValue()));
        }
        log("\n");
    }

    // 1. Create a Selector
    selector=Selector.open();

    // Create a thread pool (Executor)
    executor=new PooledExecutor(MAX_THREAD_POOL_SIZE);

    for (Iterator it=mappings.keySet().iterator(); it.hasNext();) {
        key=(MyInetSocketAddress) it.next();
        value=(MyInetSocketAddress) mappings.get(key);

        // if either source or destination are SSL, we cannot use JDK 1.4
        // NIO selectors, but have to fall back on separate threads per connection

        if (key.ssl() || value.ssl()) {
            // if(2 == 2) {
            SocketAcceptor acceptor=new SocketAcceptor(key, value);
            executor.execute(acceptor);
            continue;
        }

        // 2. Create a ServerSocketChannel
        sock_channel=ServerSocketChannel.open();
        sock_channel.configureBlocking(false);
        sock_channel.socket().bind(key);

        // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on
        //    select(). That way we can associate it with the mappings hashmap to find the corresponding
        //    value
        sock_channel.register(selector, SelectionKey.OP_ACCEPT, key);
    }

    // 4. Start main loop. won't return until CTRL-C'ed        
    loop(selector);
}