use of java.nio.channels.Selector in project smarthome by eclipse.
the class LifxLightDiscovery method handlePacket.
private void handlePacket(Packet packet, InetSocketAddress address) {
logger.trace("Discovery : Packet type '{}' received from '{}' for '{}' with sequence '{}' and source '{}'", new Object[] { packet.getClass().getSimpleName(), address.toString(), packet.getTarget().getHex(), packet.getSequence(), Long.toString(packet.getSource(), 16) });
if (packet.getSource() == sourceId || packet.getSource() == 0) {
MACAddress macAddress = packet.getTarget();
DiscoveredLight light = discoveredLights.get(macAddress);
if (packet instanceof StateServiceResponse) {
int port = (int) ((StateServiceResponse) packet).getPort();
if (port != 0) {
try {
InetSocketAddress socketAddress = new InetSocketAddress(address.getAddress(), port);
if (light == null || (!socketAddress.equals(light.socketAddress))) {
if (light != null) {
light.cancelUnicastKey();
}
Selector lightSelector = selector;
if (lightSelector != null) {
String logId = getLogId(macAddress, socketAddress);
light = new DiscoveredLight(lightSelector, macAddress, socketAddress, logId, openUnicastChannel(lightSelector, logId, socketAddress));
discoveredLights.put(macAddress, light);
}
}
} catch (Exception e) {
logger.warn("{} while connecting to IP address: {}", e.getClass().getSimpleName(), e.getMessage());
return;
}
}
} else if (light != null) {
if (packet instanceof StateLabelResponse) {
light.label = ((StateLabelResponse) packet).getLabel().trim();
} else if (packet instanceof StateVersionResponse) {
try {
light.product = Product.getProductFromProductID(((StateVersionResponse) packet).getProduct());
light.productVersion = ((StateVersionResponse) packet).getVersion();
} catch (IllegalArgumentException e) {
logger.debug("Discovered an unsupported light ({}): {}", light.macAddress.getAsLabel(), e.getMessage());
light.supportedProduct = false;
}
}
}
if (light != null && light.isDataComplete()) {
try {
thingDiscovered(createDiscoveryResult(light));
} catch (IllegalArgumentException e) {
logger.trace("{} while creating discovery result of light ({})", e.getClass().getSimpleName(), light.logId, e);
}
}
}
}
use of java.nio.channels.Selector in project spf4j by zolyfarkas.
the class TcpServerTest method testRejectingServer.
@Test(expected = IOException.class, timeout = 10000)
public void testRejectingServer() throws IOException, InterruptedException {
String testSite = "localhost";
ForkJoinPool pool = new ForkJoinPool(1024);
try (TcpServer rejServer = new TcpServer(pool, new ClientHandler() {
@Override
public void handle(final Selector serverSelector, final SocketChannel clientChannel, final ExecutorService exec, final BlockingQueue<Runnable> tasksToRunBySelector, final UpdateablePriorityQueue<DeadlineAction> deadlineActions) throws IOException {
clientChannel.configureBlocking(true);
ByteBuffer allocate = ByteBuffer.allocate(1024);
// read something
clientChannel.read(allocate);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
allocate.flip();
clientChannel.write(allocate);
clientChannel.close();
}
}, 1980, 10)) {
rejServer.startAsync().awaitRunning();
try (TcpServer server = new TcpServer(pool, new ProxyClientHandler(HostAndPort.fromParts(testSite, 1980), null, null, 10000, 5000), 1981, 10)) {
server.startAsync().awaitRunning();
byte[] readfromSite = readfromSite("http://localhost:1981");
// probably wrong charset assumtion
LOG.debug("Response: {}", new String(readfromSite, StandardCharsets.UTF_8));
}
}
}
use of java.nio.channels.Selector in project jetty.project by eclipse.
the class NIOTest method testSelector.
@Test
public void testSelector() throws Exception {
ServerSocket acceptor = new ServerSocket(0);
Selector selector = Selector.open();
// Create client server socket pair
SocketChannel client = SocketChannel.open(acceptor.getLocalSocketAddress());
Socket server = acceptor.accept();
server.setTcpNoDelay(true);
// Make the client non blocking and register it with selector for reads
client.configureBlocking(false);
SelectionKey key = client.register(selector, SelectionKey.OP_READ);
// assert it is not selected
assertTrue(key.isValid());
assertFalse(key.isReadable());
assertEquals(0, key.readyOps());
// try selecting and assert nothing selected
int selected = selector.selectNow();
assertEquals(0, selected);
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertFalse(key.isReadable());
assertEquals(0, key.readyOps());
// Write a byte from server to client
server.getOutputStream().write(42);
server.getOutputStream().flush();
// select again and assert selection found for read
selected = selector.select(1000);
assertEquals(1, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// select again and see that it is not reselect, but stays selected
selected = selector.select(100);
assertEquals(0, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// read the byte
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = client.read(buf);
assertEquals(1, len);
buf.flip();
assertEquals(42, buf.get());
buf.clear();
// But this does not change the key
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// Even if we select again ?
selected = selector.select(100);
assertEquals(0, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// Unless we remove the key from the select set
// and then it is still flagged as isReadable()
selector.selectedKeys().clear();
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// Now if we select again - it is still flagged as readable!!!
selected = selector.select(100);
assertEquals(0, selected);
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1, key.readyOps());
// Only when it is selected for something else does that state change.
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
selected = selector.select(1000);
assertEquals(1, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isWritable());
assertFalse(key.isReadable());
assertEquals(SelectionKey.OP_WRITE, key.readyOps());
}
use of java.nio.channels.Selector in project hazelcast by hazelcast.
the class SocketAcceptorThread method rebuildSelector.
private void rebuildSelector() throws IOException {
selectorRecreateCount.inc();
// cancel existing selection key, register new one on the new selector
selectionKey.cancel();
closeSelector();
Selector newSelector = Selector.open();
selector = newSelector;
selectionKey = serverSocketChannel.register(newSelector, SelectionKey.OP_ACCEPT);
}
use of java.nio.channels.Selector in project tomcat by apache.
the class NioChannel method getAttachment.
public Object getAttachment() {
Poller pol = getPoller();
Selector sel = pol != null ? pol.getSelector() : null;
SelectionKey key = sel != null ? getIOChannel().keyFor(sel) : null;
Object att = key != null ? key.attachment() : null;
return att;
}
Aggregations