当前位置: 首页>>代码示例>>Java>>正文


Java Selector.select方法代码示例

本文整理汇总了Java中java.nio.channels.Selector.select方法的典型用法代码示例。如果您正苦于以下问题:Java Selector.select方法的具体用法?Java Selector.select怎么用?Java Selector.select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.Selector的用法示例。


在下文中一共展示了Selector.select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import java.nio.channels.Selector; //导入方法依赖的package包/类
@Override
public void run() {
    final Selector tSelector = this.selector;
    for (; ; ) {
        try {
            tSelector.select(1000L);
            connect(tSelector);
            Set<SelectionKey> keys = tSelector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid() && key.isConnectable()) {
                        finishConnect(key, att);
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Exception e) {
            LOGGER.info(name, e);
        }
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:26,代码来源:NIOConnector.java

示例2: run

import java.nio.channels.Selector; //导入方法依赖的package包/类
@Override
public void run() {
	final Selector tSelector = this.selector;
	//轮询发现新连接请求
	for (;;) {
		++acceptCount;
		try {
			// 阻塞的,当超时,有注册的响应事件,或者被执行wakeup方法时继续
		    tSelector.select(1000L);
			Set<SelectionKey> keys = tSelector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					if (key.isValid() && key.isAcceptable()) {
						accept();
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(getName(), e);
		}
	}
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:27,代码来源:NIOAcceptor.java

示例3: run

import java.nio.channels.Selector; //导入方法依赖的package包/类
@Override
public void run() {
    final Selector tSelector = this.selector;
    for (; ; ) {
        try {
            tSelector.select(1000L);
            Set<SelectionKey> keys = tSelector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    if (key.isValid() && key.isAcceptable()) {
                        accept();
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Exception e) {
            LOGGER.info(getName(), e);
        }
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:24,代码来源:NIOAcceptor.java

示例4: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    final Selector sel = Selector.open();

    Runnable r = new Runnable() {
        public void run() {
            try {
                sel.select();
            } catch (IOException x) {
                x.printStackTrace();
            }
        }
    };

    // start thread to block in Selector
    Thread t = new Thread(r);
    t.start();

    // give thread time to start
    Thread.sleep(1000);

    // interrupt, close, and wakeup is the magic sequence to provoke the NPE
    t.interrupt();
    sel.close();
    sel.wakeup();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:26,代码来源:WakeupAfterClose.java

示例5: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String argv[]) throws Exception {
    int waitTime = 4000;
    Selector selector = Selector.open();
    try {
        selector.wakeup();

        long t1 = System.currentTimeMillis();
        selector.select(waitTime);
        long t2 = System.currentTimeMillis();
        long totalTime = t2 - t1;

        if (totalTime > waitTime)
            throw new RuntimeException("Test failed");
    } finally {
        selector.close();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:WakeupSpeed.java

示例6: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
//    创建ServerSocketChannel,监听8080端口
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8080));
//    设置为非阻塞模式
        ssc.configureBlocking(false);
//    为ssc注册选择器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
//    创建处理器
        while (true) {
//    等待请求,每次等待阻塞3s,超过3s后线程继续向下运行,
//    如果传入0或者不传参数将一直阻塞
            if (selector.select(3000) == 0) {
                continue;
            }
//    获取待处理的SelectionKey
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
//    启动新线程处理SelectionKey
                new Thread(new HttpHandler(key)).run();
//    处理完后,从待处理的SelectionKey迭代器中移除当前所使用的key
                keyIter.remove();
            }
        }
    }
 
开发者ID:tomoncle,项目名称:JavaStudy,代码行数:28,代码来源:HttpTest.java

示例7: run

import java.nio.channels.Selector; //导入方法依赖的package包/类
@Override
public void run() {
	final Selector tSelector = this.selector;
	for (;;) {
		++connectCount;
		try {
			// 查看有无连接就绪 阻塞的
			tSelector.select(1000L);
			connect(tSelector);
			Set<SelectionKey> keys = tSelector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(name, e);
		}
	}
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:28,代码来源:NIOConnector.java

示例8: run

import java.nio.channels.Selector; //导入方法依赖的package包/类
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++connectCount;
		try {
			//查看有无连接就绪
			selector.select( 1000L );
			connect(selector);
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key: keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(name, e);
		}
	}
}
 
开发者ID:variflight,项目名称:feeyo-redisproxy,代码行数:28,代码来源:NIOConnector.java

示例9: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    final Selector sel = Selector.open();

    Runnable r = new Runnable() {
        public void run() {
            try {
                sel.select();
            } catch (IOException x) {
                x.printStackTrace();
            } catch (ClosedSelectorException y) {
                System.err.println
                    ("Caught expected ClosedSelectorException");
            }
        }
    };

    // start thread to block in Selector
    Thread t = new Thread(r);
    t.start();

    // give thread time to start
    Thread.sleep(1000);

    // interrupt, close, and wakeup is the magic sequence to provoke the NPE
    t.interrupt();
    sel.close();
    sel.wakeup();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:WakeupAfterClose.java

示例10: select

import java.nio.channels.Selector; //导入方法依赖的package包/类
private void select() throws IOException {
    Selector selector = this.selector;
    try {
        int selectCnt = 0;
        long currentNanoTime = System.nanoTime();
        long selectDeadLineNanos = currentNanoTime + TimeUnit.SECONDS.toNanos(1);
        for (;;) {
            long timeoutMillis = (selectDeadLineNanos - currentNanoTime + 500000L) / 1000000L;
            if (timeoutMillis <= 0) {
                if (selectCnt == 0) {
                    selector.selectNow();
                    selectCnt = 1;
                }
                break;
            }

            int selectedKeys = selector.select(timeoutMillis);
            selectCnt++;

            if (selectedKeys != 0) {
                break;
            }

            if (selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) {
                LOGGER.warn("Selector.select() returned prematurely {} times in a row; rebuilding selector.", selectCnt);

                rebuildSelector();
                selector = this.selector;

                // 重新select,填充 selectedKeys
                selector.selectNow();
                selectCnt = 1;
                break;
            }

            currentNanoTime = System.nanoTime();
        }

        if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Selector.select() returned prematurely {} times in a row.", selectCnt - 1);
            }
        }
    } catch (CancelledKeyException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector - JDK bug?", e);
        }
    }
}
 
开发者ID:lemonJun,项目名称:TakinRPC,代码行数:50,代码来源:NioSelectorLoop.java

示例11: start

import java.nio.channels.Selector; //导入方法依赖的package包/类
@SuppressWarnings("InfiniteLoopStatement")
public void start() throws Exception {

    try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
        serverSocketChannel.bind(new InetSocketAddress("localhost", PORT));

        serverSocketChannel.configureBlocking(false); //non blocking mode
        int ops = SelectionKey.OP_ACCEPT;
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, ops, null);

        logger.info("Started on port: " + PORT);

        while (true) {
            selector.select();//blocks
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                try {
                    if (key.isAcceptable()) {
                        SocketChannel client = serverSocketChannel.accept(); //non blocking accept
                        System.out.println("Connection Accepted: " + client.getLocalAddress());

                        client.configureBlocking(false);
                        client.register(selector, SelectionKey.OP_READ);

                    } else if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();

                        ByteBuffer buffer = ByteBuffer.allocate(CAPACITY);
                        int read = channel.read(buffer);
                        if (read != -1) {
                            String result = new String(buffer.array()).trim();
                            if (!result.isEmpty())
                                System.out.println("Message received: " + result + " from: " + channel.getRemoteAddress());
                        } else {
                            key.cancel();
                            System.out.println("Connection closed, key canceled");
                        }
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, e.getMessage());
                } finally {
                    iterator.remove();
                }
            }
        }
    }
}
 
开发者ID:vitaly-chibrikov,项目名称:otus_java_2017_06,代码行数:50,代码来源:NonBlockingLogSocketMsgServer.java

示例12: write

import java.nio.channels.Selector; //导入方法依赖的package包/类
public int write(ByteBuffer buf, NioChannel socket, Selector selector,
                 long writeTimeout, boolean block) throws IOException {
    if ( SHARED && block ) {
        return blockingSelector.write(buf,socket,writeTimeout);
    }
    SelectionKey key = null;
    int written = 0;
    boolean timedout = false;
    int keycount = 1; //assume we can write
    long time = System.currentTimeMillis(); //start the timeout timer
    try {
        while ( (!timedout) && buf.hasRemaining() ) {
            int cnt = 0;
            if ( keycount > 0 ) { //only write if we were registered for a write
                cnt = socket.write(buf); //write the data
                if (cnt == -1) throw new EOFException();

                written += cnt;
                if (cnt > 0) {
                    time = System.currentTimeMillis(); //reset our timeout timer
                    continue; //we successfully wrote, try again without a selector
                }
                if (cnt==0 && (!block)) break; //don't block
            }
            if ( selector != null ) {
                //register OP_WRITE to the selector
                if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE);
                else key.interestOps(SelectionKey.OP_WRITE);
                keycount = selector.select(writeTimeout);
            }
            if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout;
        }//while
        if ( timedout ) throw new SocketTimeoutException();
    } finally {
        if (key != null) {
            key.cancel();
            if (selector != null) selector.selectNow();//removes the key from this selector
        }
    }
    return written;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:42,代码来源:NioSelectorPool.java

示例13: write

import java.nio.channels.Selector; //导入方法依赖的package包/类
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block)
		throws IOException {
	if (SHARED && block) {
		return blockingSelector.write(buf, socket, writeTimeout);
	}
	SelectionKey key = null;
	int written = 0;
	boolean timedout = false;
	int keycount = 1; // assume we can write
	long time = System.currentTimeMillis(); // start the timeout timer
	try {
		while ((!timedout) && buf.hasRemaining()) {
			int cnt = 0;
			if (keycount > 0) { // only write if we were registered for a
								// write
				cnt = socket.write(buf); // write the data
				if (cnt == -1)
					throw new EOFException();

				written += cnt;
				if (cnt > 0) {
					time = System.currentTimeMillis(); // reset our timeout
														// timer
					continue; // we successfully wrote, try again without a
								// selector
				}
				if (cnt == 0 && (!block))
					break; // don't block
			}
			if (selector != null) {
				// register OP_WRITE to the selector
				if (key == null)
					key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE);
				else
					key.interestOps(SelectionKey.OP_WRITE);
				keycount = selector.select(writeTimeout);
			}
			if (writeTimeout > 0 && (selector == null || keycount == 0))
				timedout = (System.currentTimeMillis() - time) >= writeTimeout;
		} // while
		if (timedout)
			throw new SocketTimeoutException();
	} finally {
		if (key != null) {
			key.cancel();
			if (selector != null)
				selector.selectNow();// removes the key from this selector
		}
	}
	return written;
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:52,代码来源:NioSelectorPool.java

示例14: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    Selector selector;
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        selector = Selector.open();
    }
    Member mbr = new MemberImpl("localhost", 9999, 0);
    byte seq = 0;
    byte[] buf = new byte[50000];
    Arrays.fill(buf,seq);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;

    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    seq++;
                    Arrays.fill(buf,seq);
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:77,代码来源:SocketNioValidateSend.java

示例15: main

import java.nio.channels.Selector; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    Selector selector;
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        selector = Selector.open();
    }
    Member mbr = new MemberImpl("localhost", 9999, 0);
    ChannelData data = new ChannelData();
    data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE);
    data.setAddress(mbr);
    byte[] buf = new byte[8192 * 4];
    data.setMessage(new XByteBuffer(buf,false));
    buf = XByteBuffer.createDataPackage(data);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.setTxBufSize(1024*1024);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;
    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
        selector.selectedKeys().clear();
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:79,代码来源:SocketNioSend.java


注:本文中的java.nio.channels.Selector.select方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。