use of java.nio.channels.Selector in project netty by netty.
the class NioEventLoop method select.
private void select(boolean oldWakenUp) throws IOException {
Selector selector = this.selector;
try {
int selectCnt = 0;
long currentTimeNanos = System.nanoTime();
long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos);
for (; ; ) {
long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L;
if (timeoutMillis <= 0) {
if (selectCnt == 0) {
selector.selectNow();
selectCnt = 1;
}
break;
}
// It might be pended until idle timeout if IdleStateHandler existed in pipeline.
if (hasTasks() && wakenUp.compareAndSet(false, true)) {
selector.selectNow();
selectCnt = 1;
break;
}
int selectedKeys = selector.select(timeoutMillis);
selectCnt++;
if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) {
// - a scheduled task is ready for processing
break;
}
if (Thread.interrupted()) {
// See https://github.com/netty/netty/issues/2426
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely because " + "Thread.currentThread().interrupt() was called. Use " + "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop.");
}
selectCnt = 1;
break;
}
long time = System.nanoTime();
if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) {
// timeoutMillis elapsed without anything selected.
selectCnt = 1;
} else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) {
// The selector returned prematurely many times in a row.
// Rebuild the selector to work around the problem.
logger.warn("Selector.select() returned prematurely {} times in a row; rebuilding Selector {}.", selectCnt, selector);
rebuildSelector();
selector = this.selector;
// Select again to populate selectedKeys.
selector.selectNow();
selectCnt = 1;
break;
}
currentTimeNanos = time;
}
if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) {
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely {} times in a row for Selector {}.", selectCnt - 1, selector);
}
}
} catch (CancelledKeyException e) {
if (logger.isDebugEnabled()) {
logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector {} - JDK bug?", selector, e);
}
// Harmless exception - log anyway
}
}
use of java.nio.channels.Selector in project opennms by OpenNMS.
the class SelectorTrackerTest method test.
@Test
public void test() throws IOException {
Selector selector = Selector.open();
assertTrue(selector.isOpen());
selector.close();
assertFalse(selector.isOpen());
DatagramChannel c = DatagramChannel.open();
DatagramSocket s = c.socket();
s.setSoTimeout(1000);
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, 1024, InetAddress.getLocalHost(), 7);
s.send(p);
}
use of java.nio.channels.Selector in project voltdb by VoltDB.
the class TLSHandshaker method handshake.
public boolean handshake() throws IOException {
ByteBuffer txNetData = (ByteBuffer) ByteBuffer.allocate(m_appsz).clear();
ByteBuffer clearData = (ByteBuffer) ByteBuffer.allocate(CipherExecutor.FRAME_SIZE).clear();
SSLEngineResult result = null;
m_eng.beginHandshake();
HandshakeStatus status = m_eng.getHandshakeStatus();
boolean isBlocked = m_sc.isBlocking();
synchronized (m_sc.blockingLock()) {
isBlocked = m_sc.isBlocking();
if (isBlocked) {
m_sc.configureBlocking(false);
}
}
Selector selector = Selector.open();
m_sc.register(selector, SelectionKey.OP_READ);
try {
while (status != HandshakeStatus.FINISHED && status != HandshakeStatus.NOT_HANDSHAKING) {
switch(status) {
case NEED_UNWRAP:
if (selector.select(2) == 1 && canread(selector)) {
if (m_sc.read(m_rxNetData) < 0) {
if (m_eng.isInboundDone() && m_eng.isOutboundDone()) {
return false;
}
try {
m_eng.closeInbound();
} catch (SSLException ingnoreIt) {
}
m_eng.closeOutbound();
status = m_eng.getHandshakeStatus();
break;
}
}
m_rxNetData.flip();
try {
result = m_eng.unwrap(m_rxNetData, clearData);
m_rxNetData.compact();
status = m_eng.getHandshakeStatus();
} catch (SSLException e) {
m_eng.closeOutbound();
throw e;
}
switch(result.getStatus()) {
case OK:
break;
case BUFFER_OVERFLOW:
clearData = expand(clearData, false);
break;
case BUFFER_UNDERFLOW:
// in this state until data shows up in m_rxNetData.
break;
case CLOSED:
if (m_eng.isOutboundDone()) {
return false;
} else {
m_eng.closeOutbound();
status = m_eng.getHandshakeStatus();
}
break;
default:
throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
}
break;
case NEED_WRAP:
txNetData.clear();
try {
result = m_eng.wrap(clearData, txNetData);
status = m_eng.getHandshakeStatus();
} catch (SSLException e) {
m_eng.closeOutbound();
throw e;
}
switch(result.getStatus()) {
case OK:
txNetData.flip();
while (txNetData.hasRemaining()) {
m_sc.write(txNetData);
}
break;
case BUFFER_OVERFLOW:
clearData = expand(txNetData, false);
break;
case BUFFER_UNDERFLOW:
throw new SSLException("Buffer underflow occured after a wrap");
case CLOSED:
txNetData.flip();
while (txNetData.hasRemaining()) {
m_sc.write(txNetData);
}
m_rxNetData.clear();
status = m_eng.getHandshakeStatus();
break;
default:
throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
}
break;
case NEED_TASK:
Runnable task;
while ((task = m_eng.getDelegatedTask()) != null) {
task.run();
}
status = m_eng.getHandshakeStatus();
break;
case FINISHED:
break;
case NOT_HANDSHAKING:
break;
default:
throw new IllegalStateException("Invalid SSL handshake status" + status);
}
}
} finally {
SelectionKey sk = m_sc.keyFor(selector);
sk.cancel();
selector.close();
if (isBlocked)
synchronized (m_sc.blockingLock()) {
m_sc.configureBlocking(isBlocked);
}
}
return true;
}
use of java.nio.channels.Selector in project yyl_example by Relucent.
the class Receive method main.
public static void main(String[] args) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate(1024);
ServerSocketChannel ss = ServerSocketChannel.open();
ss.socket().bind(new InetSocketAddress(9998));
ss.configureBlocking(false);
Selector se = Selector.open();
ss.register(se, SelectionKey.OP_ACCEPT);
while (se.select() > 0) {
Set<SelectionKey> set = se.selectedKeys();
for (SelectionKey key : set) {
System.out.println("-------------");
SocketChannel sc = null;
try {
if (key.isAcceptable()) {
sc = ss.accept();
System.err.println("ACCEPTABLE:" + sc.socket());
sc.configureBlocking(false);
sc.register(se, SelectionKey.OP_READ);
} else if (key.isReadable()) {
sc = (SocketChannel) key.channel();
System.out.println(sc.isConnected());
sc.read(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.remaining()));
sc.write(ByteBuffer.wrap("+".getBytes()));
}
} catch (Exception e) {
key.cancel();
if (sc != null) {
sc.close();
}
e.printStackTrace();
}
}
set.clear();
}
}
use of java.nio.channels.Selector in project yyl_example by Relucent.
the class Send method main.
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9998));
while (!socketChannel.finishConnect()) {
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.write(ByteBuffer.wrap("-".getBytes()));
int index = 0;
while (true) {
if (selector.select() == 0) {
Thread.sleep(1000);
continue;
}
Set<SelectionKey> set = selector.selectedKeys();
for (SelectionKey key : set) {
int ops = key.readyOps();
if ((ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
socketChannel.write(buffer);
System.out.println("OP_CONNECT:");
}
if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
socketChannel.read(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.remaining()));
buffer.clear();
socketChannel.write(ByteBuffer.wrap(("No-" + index + " | ").getBytes()));
index++;
}
}
set.clear();
Thread.sleep(1000);
}
}
Aggregations