use of java.nio.channels.Selector in project GIPC by pdewan.
the class NioClientExp method run.
public void run() {
SelectionKey writeKey = null;
try {
// SocketChannel socketChannel = syncConnect(initRspHandler);
// globalSocketChannel = socketChannel;
// send(socketChannel, "Hello World".getBytes());
// send(socketChannel, "Goodbye World".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
while (true) {
try {
if (register) {
// globalSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
globalSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
register = false;
}
// Process any pending changes
synchronized (this.pendingChanges) {
Iterator changes = this.pendingChanges.iterator();
while (changes.hasNext()) {
ChangeRequest change = (ChangeRequest) changes.next();
switch(change.type) {
case ChangeRequest.CHANGEOPS:
SelectionKey key = change.socket.keyFor(this.selector);
key.interestOps(change.ops);
break;
case ChangeRequest.REGISTER:
// change.socket.configureBlocking(true);
SocketChannel sockChannel = change.socket;
int ops = change.ops;
Selector theSelector = selector;
sockChannel.register(theSelector, ops);
break;
}
}
this.pendingChanges.clear();
}
// Wait for an event one of the registered channels
this.selector.select();
// Iterate over the set of keys for which events are available
Iterator selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
// Check what event is available and deal with it
if (key.isConnectable()) {
this.finishConnection(key);
}
if (key.isReadable()) {
this.read(key);
}
if (key.isWritable()) {
writeKey = key;
// this.write(key);
this.serializedWrite(key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of java.nio.channels.Selector in project Mycat_plus by coderczp.
the class NIOConnector method run.
@Override
public void run() {
int invalidSelectCount = 0;
for (; ; ) {
final Selector tSelector = this.selector;
++connectCount;
try {
long start = System.nanoTime();
tSelector.select(1000L);
long end = System.nanoTime();
connect(tSelector);
Set<SelectionKey> keys = tSelector.selectedKeys();
if (keys.size() == 0 && (end - start) < SelectorUtil.MIN_SELECT_TIME_IN_NANO_SECONDS) {
invalidSelectCount++;
} else {
try {
for (SelectionKey key : keys) {
Object att = key.attachment();
if (att != null && key.isValid() && key.isConnectable()) {
finishConnect(key, att);
} else {
key.cancel();
}
}
} finally {
invalidSelectCount = 0;
keys.clear();
}
}
if (invalidSelectCount > SelectorUtil.REBUILD_COUNT_THRESHOLD) {
final Selector rebuildSelector = SelectorUtil.rebuildSelector(this.selector);
if (rebuildSelector != null) {
this.selector = rebuildSelector;
}
invalidSelectCount = 0;
}
} catch (Exception e) {
LOGGER.warn(name, e);
}
}
}
use of java.nio.channels.Selector in project tutorials by eugenp.
the class EchoServer method main.
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", 5454));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(256);
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
register(selector, serverSocket);
}
if (key.isReadable()) {
answerWithEcho(buffer, key);
}
iter.remove();
}
}
}
use of java.nio.channels.Selector in project JavaBase by SkyScraperTwc.
the class NIOTcpClient method main.
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannel.connect(new InetSocketAddress(IP_ADDRESS, PORT));
while (!socketChannel.finishConnect()) ;
new Thread(new SendRunnable(socketChannel)).start();
System.out.println("Connecting to " + IP_ADDRESS + " on " + PORT);
while (true) {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()) {
SocketChannel channel = (SocketChannel) selectionKey.channel();
StringBuilder sb = new StringBuilder();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (channel.read(byteBuffer) > 0) {
byteBuffer.flip();
sb.append(new String(byteBuffer.array()));
byteBuffer.clear();
}
System.out.println("[server] " + sb.toString());
}
iterator.remove();
}
}
}
use of java.nio.channels.Selector in project spring-integration by spring-projects.
the class TcpNioConnectionTests method testMemoryLeak.
@Test
public void testMemoryLeak() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ServerSocket> serverSocket = new AtomicReference<>();
this.executor.execute(() -> {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
serverSocket.set(server);
latch.countDown();
Socket socket = server.accept();
byte[] b = new byte[6];
readFully(socket.getInputStream(), b);
} catch (Exception e) {
e.printStackTrace();
}
});
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", serverSocket.get().getLocalPort());
factory.setApplicationEventPublisher(nullPublisher);
factory.setNioHarvestInterval(100);
factory.start();
try {
TcpConnection connection = factory.getConnection();
Map<SocketChannel, TcpNioConnection> connections = factory.getConnections();
assertEquals(1, connections.size());
connection.close();
assertTrue(!connection.isOpen());
TestUtils.getPropertyValue(factory, "selector", Selector.class).wakeup();
int n = 0;
while (connections.size() > 0) {
Thread.sleep(100);
if (n++ > 100) {
break;
}
}
assertEquals(0, connections.size());
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected exception " + e);
}
factory.stop();
serverSocket.get().close();
}
Aggregations