use of java.nio.channels.Selector in project smarthome by eclipse.
the class LifxLightCommunicationHandler method start.
public void start() {
try {
lock.lock();
logger.debug("{} : Starting communication handler", logId);
logger.debug("{} : Using '{}' as source identifier", logId, Long.toString(sourceId, 16));
ScheduledFuture<?> localNetworkJob = networkJob;
if (localNetworkJob == null || localNetworkJob.isCancelled()) {
networkJob = scheduler.scheduleWithFixedDelay(this::receiveAndHandlePackets, 0, PACKET_INTERVAL, TimeUnit.MILLISECONDS);
}
currentLightState.setOffline();
Selector localSelector = Selector.open();
selector = localSelector;
if (isBroadcastEnabled()) {
broadcastKey = openBroadcastChannel(selector, logId, broadcastPort);
selectorContext = new LifxSelectorContext(localSelector, sourceId, sequenceNumberSupplier, logId, host, macAddress, broadcastKey, unicastKey);
broadcastPacket(new GetServiceRequest());
} else {
unicastKey = openUnicastChannel(selector, logId, host);
selectorContext = new LifxSelectorContext(localSelector, sourceId, sequenceNumberSupplier, logId, host, macAddress, broadcastKey, unicastKey);
sendPacket(new GetServiceRequest());
}
} catch (IOException e) {
logger.error("{} while starting LIFX communication handler for light '{}' : {}", e.getClass().getSimpleName(), logId, e.getMessage(), e);
} finally {
lock.unlock();
}
}
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 iobserve-analysis by research-iobserve.
the class MultipleConnectionTcpReaderStage method execute.
@Override
protected void execute() {
try {
final ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress(this.inputPort));
serverSocket.configureBlocking(false);
final Selector readSelector = Selector.open();
while (this.isActive()) {
final SocketChannel socketChannel = serverSocket.accept();
if (socketChannel != null) {
this.logger.debug("Connection from {}.", socketChannel.getRemoteAddress().toString());
// add socketChannel to list of channels
socketChannel.configureBlocking(false);
final SelectionKey key = socketChannel.register(readSelector, SelectionKey.OP_READ);
final Connection connection = new Connection(socketChannel, this.bufferSize);
key.attach(connection);
}
final int readReady = readSelector.selectNow();
if (readReady > 0) {
final Set<SelectionKey> selectedKeys = readSelector.selectedKeys();
final Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
final SelectionKey key = keyIterator.next();
this.readFromSocket(key);
keyIterator.remove();
}
selectedKeys.clear();
}
}
} catch (final ClosedByInterruptException e) {
this.logger.info("External shutdown called");
} catch (final IOException e) {
this.logger.error("Cannot establish listening port", e);
} finally {
this.workCompleted();
}
}
use of java.nio.channels.Selector in project GIPC by pdewan.
the class NioServer method initSelector.
private Selector initSelector() throws IOException {
// Create a new selector
Selector socketSelector = SelectorProvider.provider().openSelector();
// Create a new non-blocking server socket channel
this.serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
// Bind the server socket to the specified address and port
InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
serverChannel.socket().bind(isa);
// Register the server socket channel, indicating an interest in
// accepting new connections
serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
return socketSelector;
}
use of java.nio.channels.Selector in project GIPC by pdewan.
the class NioClientExp method syncWrite.
private void syncWrite(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
int ops = key.interestOps();
key.cancel();
// socketChannel.register(null, 0);
SelectableChannel retChannel = socketChannel.configureBlocking(true);
OutputStream socketOutputStream = socketChannel.socket().getOutputStream();
// synchronized (this.pendingData) {
List queue = (List) this.pendingData.get(socketChannel);
// Write until there's not more data ...
while (!queue.isEmpty()) {
ByteBuffer buf = (ByteBuffer) queue.get(0);
// socketChannel.write(buf);
// OutputStream socketOutputStream = socketChannel.socket().getOutputStream();
socketOutputStream.write(buf.array());
// socketChannel.register(this.selector, ChangeRequest.CHANGEOPS);
// this seems to fil up
// if (buf.remaining() > 0) {
// // ... or the socket's buffer fills up
// break;
// }
queue.remove(0);
}
retChannel = socketChannel.configureBlocking(false);
// initSelector();
Selector theSelector = this.selector;
// int ops = ChangeRequest.CHANGEOPS;
socketChannel.register(theSelector, ops);
if (queue.isEmpty()) {
// We wrote away all data, so we're no longer interested
// in writing on this socket. Switch back to waiting for
// data.
key.interestOps(SelectionKey.OP_READ);
}
}
Aggregations