/** * Serves the incoming connections. * * @throws IOException * @throws DirectoryException */ private void serveIncomingConnections() throws IOException, DirectoryException { int selectorState = selector.select(); // We can't rely on return value of select to determine if any keys // are ready. // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4850373 for (Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); iterator.hasNext(); ) { SelectionKey key = iterator.next(); iterator.remove(); if (key.isAcceptable()) { // Accept the new client connection. ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel clientChannel = serverChannel.accept(); if (clientChannel != null) { acceptConnection(clientChannel); } } if (selectorState == 0 && enabled && !shutdownRequested && logger.isTraceEnabled()) { // Selected keys was non empty but select() returned 0. // Log warning and hope it blocks on the next select() call. logger.trace( "Selector.select() returned 0. " + "Selected Keys: %d, Interest Ops: %d, Ready Ops: %d ", selector.selectedKeys().size(), key.interestOps(), key.readyOps()); } } }
/** Selects on sockets and informs their Communicator when there is something to do. */ public void communicate(int timeout) { try { selector.select(timeout); } catch (IOException e) { // Not really sure why/when this happens yet return; } Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) continue; // WHY Communicator communicator = (Communicator) key.attachment(); if (key.isReadable()) communicator.onReadable(); if (key.isWritable()) communicator.onWritable(); if (key.isAcceptable()) communicator.onAcceptable(); } // Go through the queue and handle each communicator while (!queue.isEmpty()) { Communicator c = queue.poll(); c.onMemo(); } }
public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(PORT)); System.out.println("Server listening at port : " + PORT); serverSocketChannel.configureBlocking(false); Selector selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { int n = selector.select(); if (n == 0) { continue; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); System.out.println("accept client : " + sc); acceptClient(sc); } if (key.isReadable()) { readData(key); } it.remove(); } } }
@Override public void run() { selectorManager.notifyReady(); while (selectorManager.isStarted() && selector.isOpen()) { try { beforeSelect(); wakenUp.set(false); long before = -1; // Wether to look jvm bug if (isNeedLookingJVMBug()) { before = System.currentTimeMillis(); } long wait = DEFAULT_WAIT; if (nextTimeout > 0) { wait = nextTimeout; } int selected = selector.select(wait); if (selected == 0) { if (before != -1) { lookJVMBug(before, selected, wait); } selectTries++; // check tmeout and idle nextTimeout = checkSessionTimeout(); continue; } else { selectTries = 0; } } catch (ClosedSelectorException e) { break; } catch (IOException e) { log.error("Reactor select error", e); if (selector.isOpen()) { continue; } else { break; } } Set<SelectionKey> selectedKeys = selector.selectedKeys(); gate.lock(); try { postSelect(selectedKeys, selector.keys()); dispatchEvent(selectedKeys); } finally { gate.unlock(); } } if (selector != null) { if (selector.isOpen()) { try { controller.closeChannel(selector); selector.close(); } catch (IOException e) { controller.notifyException(e); log.error("stop reactor error", e); } } } }
/* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { while (!stop) { try { selector.select(1000); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(key); } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) key.channel().close(); } } } } catch (Throwable t) { t.printStackTrace(); } } // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭,所以不需要重复释放资源 if (selector != null) try { selector.close(); } catch (IOException e) { e.printStackTrace(); } }
public boolean waitEvent(long timeout) { int rc = 0; try { if (timeout == 0) { // waitEvent(0) is called every read/send of SocketBase // instant readiness is not strictly required // On the other hand, we can save lots of system call and increase performance return rcursor < wcursor.get(); } else if (timeout < 0) { rc = selector.select(0); } else { rc = selector.select(timeout); } } catch (IOException e) { throw new ZError.IOException(e); } if (rc == 0) { return false; } selector.selectedKeys().clear(); return true; }
@Override public void run() { while (!Thread.interrupted()) { try { selector.select(); } catch (IOException e) { continue; } processRegisterChannels(); Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { try { handle(key); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable throwable) { Logger.error("ChannelKey handle fail.", throwable); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } keys.clear(); } }
@Override public void run() { Thread.currentThread().setName(threadName); while (started) { processRegisterTaskQueue(); try { if (selector.select(1000) > 0) { Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); // 处理Key if (key.isReadable()) { processReadableKey(key); } else if (key.isWritable()) { processWritableKey(key); } } // TODO shutdown } } catch (IOException e) { logger.warn("Unexpected exception in the selector loop.", e); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException t) { // Ignore. } } } }
private void do_selection() throws IOException { // wait for events // timeout 1000ms -> check for pendingChanges at least every second if (selector.select(1000) == 0) return; // wakeup to work on selected keys Iterator keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = (SelectionKey) keys.next(); keys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { accept(key); } else if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } else if (key.isConnectable()) { connect(key); } } }
@Override public void run() { try { System.out.println("[Server Opened]"); selector = Selector.open(); ssc.register(selector, SelectionKey.OP_ACCEPT); while (true) { int canalsPreparats = selector.select(); if (canalsPreparats == 0) { continue; } Set<SelectionKey> clausSeleccionades = selector.selectedKeys(); Iterator<SelectionKey> iterador = clausSeleccionades.iterator(); while (iterador.hasNext()) { SelectionKey clau = iterador.next(); // CONCURRENCIA claus // Les claus son un recurs compartit, ja que quan finalitza // el joc, el métode update() les cancela. Per aquest motiu // quan en fem us, synchronitzem el objecte, i comprovem // que siguin vàlides synchronized (this) { if (clau.isValid() && clau.isAcceptable()) { ferAccept(clau); } else if (clau.isValid() && clau.isReadable()) { rebre(clau); } } iterador.remove(); } } } catch (IOException ex) { } }
public void run() { try { while (running) { int k; try { k = selector.select(); } catch (IOException e) { manager.getLogger().info("Exception thrown by accept thread selector " + e); break; } if (k <= 0) { continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { SelectionKey key = i.next(); ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel channel; try { channel = serverChannel.accept(); } catch (IOException e) { manager.getLogger().info("Exception thrown by server socket when accepting " + e); continue; } manager.addChannel(channel); } } } finally { cleanup(); } }
public static void main(String[] argv) throws Exception { Pipe[] pipes = new Pipe[PIPES_COUNT]; Pipe pipe = Pipe.open(); Pipe.SinkChannel sink = pipe.sink(); Pipe.SourceChannel source = pipe.source(); Selector sel = Selector.open(); source.configureBlocking(false); source.register(sel, SelectionKey.OP_READ); for (int i = 0; i < PIPES_COUNT; i++) { pipes[i] = Pipe.open(); Pipe.SourceChannel sc = pipes[i].source(); sc.configureBlocking(false); sc.register(sel, SelectionKey.OP_READ); Pipe.SinkChannel sc2 = pipes[i].sink(); sc2.configureBlocking(false); sc2.register(sel, SelectionKey.OP_WRITE); } for (int i = 0; i < LOOPS; i++) { sink.write(ByteBuffer.allocate(BUF_SIZE)); int x = sel.selectNow(); sel.selectedKeys().clear(); source.read(ByteBuffer.allocate(BUF_SIZE)); } for (int i = 0; i < PIPES_COUNT; i++) { pipes[i].sink().close(); pipes[i].source().close(); } pipe.sink().close(); pipe.source().close(); sel.close(); }
@Override public void run() { final Selector selector = this.selector; for (; ; ) { ++reactCount; try { selector.select(1000L); register(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); System.out.println("attchment " + att); if (att != null && key.isValid()) { int readyOps = key.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { read((NIOConnection) att); } else if ((readyOps & SelectionKey.OP_WRITE) != 0) { write((NIOConnection) att); } else { key.cancel(); } } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
// Process keys that have become selected // void processSelectedKeys() throws IOException { for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) { // Retrieve the next key and remove it from the set SelectionKey sk = (SelectionKey) i.next(); i.remove(); // Retrieve the target and the channel Target t = (Target) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); // Attempt to complete the connection sequence try { if (sc.finishConnect()) { sk.cancel(); t.connectFinish = System.currentTimeMillis(); sc.close(); printer.add(t); } } catch (IOException x) { sc.close(); t.failure = x; printer.add(t); } } }
@Override public void run() { try { selector = Selector.open(); while (true) { processSelectionQueue(); int nKeys = selector.select(selectWaitTime); // blocking if (nKeys == 0) { continue; } else { logger.trace(String.format("Selector %d, keys num: %d", selectorNum, nKeys)); } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); logger.trace("Key operations: " + key.readyOps()); if (key.isWritable()) { doWrite(key); } } } } catch (IOException e) { throw new RuntimeException(e); } }
// actual connection logic private void _connect() throws IOException { // Continuous loop that is only supposed to end when "close" is called. selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { SelectionKey key = i.next(); i.remove(); if (key.isConnectable()) { if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } socketChannel.register(selector, SelectionKey.OP_READ); _writeHandshake(); } if (key.isReadable()) { try { _read(); } catch (NoSuchAlgorithmException nsa) { this.onError(nsa); } } } }
private void loop() { while (true) { try { selector.select(); Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) { continue; } // Check what event is available and deal with it if (key.isAcceptable()) { accept(key); } else if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
private void dispatchMessages() throws IOException { Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); EventSource source = (EventSource) key.attachment(); if (key.isValid()) { try { if (key.isAcceptable()) { EventSource newSource = source.accept(); if (newSource != null) newSources.add(newSource); } if (key.isReadable()) { source.read(); } if (key.isWritable()) { source.write(); } } catch (CancelledKeyException e) { } } it.remove(); } for (int i = 0; i < newSources.size(); i++) register(newSources.get(i)); if (!newSources.isEmpty()) newSources.clear(); }
@Override public void run() { while (true) { try { synchronized (_pendingRequest) { Iterator changes = _pendingRequest.iterator(); while (changes.hasNext()) { ChangeRequest change = (ChangeRequest) changes.next(); if (!processPendingRequest(change)) break; changes.remove(); } } // wait events from selected channels _selector.select(); Iterator selectedKeys = _selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey) selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) { continue; } processSelect(key); } } catch (Exception e) { logger.warning(Util.getErrorMessage(e)); } } }
public void run() { try { while (!flag) { System.out.println("waiting connected......."); selector.select(); Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); SelectionKey clientKey = sc.register(selector, SelectionKey.OP_READ); System.out.println(sc.socket().getInetAddress().getHostAddress() + " 已连接"); } if (key.isReadable()) { read(key); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Start the server running - accepting connections, receiving messages. If the server is already * running, it will not be started again. This method is designed to be called in its own thread * and will not return until the server is stopped. * * @throws RuntimeException if the server fails */ public void run() { // ensure that the server is not started twice if (!state.compareAndSet(State.STOPPED, State.RUNNING)) { started(true); return; } Selector selector = null; ServerSocketChannel server = null; try { selector = Selector.open(); server = ServerSocketChannel.open(); server.socket().bind(new InetSocketAddress(port)); server.configureBlocking(false); server.register(selector, SelectionKey.OP_ACCEPT); started(false); while (state.get() == State.RUNNING) { selector.select(100); // check every 100ms whether the server has been requested to stop for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) { SelectionKey key = it.next(); try { // remove key from the ready list it.remove(); if (key.isConnectable()) { ((SocketChannel) key.channel()).finishConnect(); } if (key.isAcceptable()) { // accept connection SocketChannel client = server.accept(); client.configureBlocking(false); client.socket().setTcpNoDelay(true); // channel is registered for further events such as read or write SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ); connection(acceptKey); } if (key.isReadable()) { for (ByteBuffer message : readIncomingMessage(key)) { messageReceived(message, key); } } } catch (IOException ioe) { resetKey(key); disconnected(key); } } } } catch (Throwable e) { throw new RuntimeException("Server failure: " + e.getMessage()); } finally { try { selector.close(); server.socket().close(); server.close(); state.set(State.STOPPED); stopped(); } catch (Exception e) { // do nothing - server failed } } }
private void driveClientIO() throws IOException, GearmanException { for (GearmanJobServerSession sess : sessionsMap.values()) { int interestOps = SelectionKey.OP_READ; if (sess.sessionHasDataToWrite()) { interestOps |= SelectionKey.OP_WRITE; } try { sess.getSelectionKey().interestOps(interestOps); } catch (IllegalStateException ise) { LOG.warn("Unable to drive IO for session " + sess + "," + " skipping.", ise); continue; } } ioAvailable.selectNow(); Set<SelectionKey> keys = ioAvailable.selectedKeys(); LOG.trace( "Driving IO for client " + this + ". " + keys.size() + " session(s) currently available for IO"); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); GearmanJobServerSession s = sessionsMap.get(key); s.driveSessionIO(); } }
public void serve(int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); // Binds the server to the selected port ss.bind(address); // Opens the Selector for handling channels Selector selector = Selector.open(); // Registers the ServerSocket with the Selector to accept connections serverChannel.register(selector, SelectionKey.OP_ACCEPT); final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes()); while (true) { try { // Waits for new events to process; blocks until the next incoming event selector.select(); } catch (IOException e) { e.printStackTrace(); break; } // Obtains all SelectionKey instances that received events Set<SelectionKey> readyKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = readyKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); iterator.remove(); try { // Checks if the event is a new connection ready to be accepted if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); client.configureBlocking(false); // Accepts client and registers it with the selector client.register( selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate()); System.out.println("Accepted connection from " + client); } // Checks if the socket is ready for writing data if (key.isWritable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = (ByteBuffer) key.attachment(); while (buffer.hasRemaining()) { // Writes data to the connected client if (client.write(buffer) == 0) { break; } } // Closes the connection client.close(); } } catch (IOException e) { key.cancel(); try { key.channel().close(); } catch (IOException e1) { } } } } }
public void run() { while (true) { try { synchronized (changeRequests) { Iterator changes = changeRequests.iterator(); while (changes.hasNext()) { ChangeRequest change = (ChangeRequest) changes.next(); switch (change.type) { case ChangeRequest.CHANGEOPS: SelectionKey key = change.socket.keyFor(selector); key.interestOps(change.ops); } } changeRequests.clear(); } selector.select(); Iterator selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey) selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) continue; if (key.isAcceptable()) accept(key); else if (key.isReadable()) read(key); else if (key.isWritable()) write(key); } } catch (IOException e) { e.printStackTrace(); } } }
@Override public void establish() throws IOException { discoverySelector = Selector.open(); serverSocketChannel.register(discoverySelector, SelectionKey.OP_ACCEPT); int slaveCount = 0; while (slaveCount < slaves.length) { log.info("Awaiting registration from " + (slaves.length - slaveCount) + " slaves."); discoverySelector.select(); Set<SelectionKey> keySet = discoverySelector.selectedKeys(); Iterator<SelectionKey> it = keySet.iterator(); while (it.hasNext()) { SelectionKey selectionKey = it.next(); it.remove(); if (!selectionKey.isValid()) { continue; } ServerSocketChannel srvSocketChannel = (ServerSocketChannel) selectionKey.channel(); SocketChannel socketChannel = srvSocketChannel.accept(); int slaveIndex = readInt(socketChannel); if (slaveIndex < 0) { for (int i = 0; i < slaves.length; ++i) { if (slaves[i] == null) { slaveIndex = i; break; } } } else if (slaveIndex >= slaves.length) { throw new IllegalArgumentException( "Slave requests invalid slaveIndex " + slaveIndex + " (expected " + slaves.length + " slaves)"); } else if (slaves[slaveIndex] != null) { throw new IllegalArgumentException( "Slave requests slaveIndex " + slaveIndex + " but this was already assigned to " + slaves[slaveIndex].getRemoteAddress()); } writeInt(socketChannel, slaveIndex); writeInt(socketChannel, slaves.length); slaves[slaveIndex] = socketChannel; slaveCount++; slave2Index.put(socketChannel, slaveIndex); this.readBufferMap.put(socketChannel, ByteBuffer.allocate(DEFAULT_READ_BUFF_CAPACITY)); socketChannel.configureBlocking(false); log.trace( "Added new slave connection " + slaveIndex + " from: " + socketChannel.socket().getInetAddress()); } } mcastBuffer = ByteBuffer.allocate(DEFAULT_WRITE_BUFF_CAPACITY); log.info("Connection established from " + slaveCount + " slaves."); }
/** * The background thread that adds sockets to the Poller, checks the poller for triggered events * and hands the associated socket off to an appropriate processor as events occur. */ @Override public void run() { // Loop until destroy() is called while (true) { boolean hasEvents = false; try { if (!close) { hasEvents = events(); if (wakeupCounter.getAndSet(-1) > 0) { // if we are here, means we have other stuff to do // do a non blocking select keyCount = selector.selectNow(); } else { keyCount = selector.select(selectorTimeout); } wakeupCounter.set(0); } if (close) { events(); timeout(0, false); try { selector.close(); } catch (IOException ioe) { log.error(sm.getString("endpoint.nio.selectorCloseFail"), ioe); } break; } } catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("", x); continue; } // either we timed out or we woke up, process events first if (keyCount == 0) hasEvents = (hasEvents | events()); Iterator<SelectionKey> iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null; // Walk through the collection of ready keys and dispatch // any active event. while (iterator != null && iterator.hasNext()) { SelectionKey sk = iterator.next(); NioSocketWrapper attachment = (NioSocketWrapper) sk.attachment(); // Attachment may be null if another thread has called // cancelledKey() if (attachment == null) { iterator.remove(); } else { iterator.remove(); processKey(sk, attachment); } } // while // process timeouts timeout(keyCount, hasEvents); } // while stopLatch.countDown(); }
/** * Execute the Selector.select(...) operations. * * @param ctx {@link Context} * @return {@link Set} of {@link SelectionKey} */ public Set<SelectionKey> select(Context ctx) throws IOException { if (postponedTasks.isEmpty()) { selector.select(selectTimeout); } else { selector.selectNow(); } return selector.selectedKeys(); }
public void run() { try { SocketChannel sc = SocketChannel.open(); InetSocketAddress sinaAddr = new InetSocketAddress("sina.com", 80); sc.socket().connect(sinaAddr); // init a selector via helper class selector provider Selector aSel = SelectorProvider.provider().openSelector(); Socket soc = new Socket("host", 80); soc.getChannel().register(aSel, SelectionKey.OP_ACCEPT); // init a channel for server socket. method 1 ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(true); // method 2, get server socket first, then init its channel ServerSocket ss = new ServerSocket(); ServerSocketChannel ssc2 = ss.getChannel(); // set socket channel as non blocking. ssc.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress("localhost", 9999); ssc.socket().bind(isa); SelectionKey acceptKey = ssc.register(aSel, SelectionKey.OP_ACCEPT); int keysAdded = 0; while ((keysAdded = aSel.select()) > 0) { Set readyKeys = aSel.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); ServerSocketChannel n = (ServerSocketChannel) sk.channel(); // now we got a new socket and its channel after accept in server Socket s = n.accept().socket(); SocketChannel socketChannel = s.getChannel(); socketChannel.register(aSel, SelectionKey.OP_READ); } } } catch (Exception e) { } }
private void dispatch() throws IOException { sel.select(); for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); Handler h = (Handler) sk.attachment(); h.handle(sk); } }
protected String sendAndReceive(byte[] payload) throws IOException { ByteBuffer sbuf = ByteBuffer.wrap(payload); ByteBuffer rbuf = ByteBuffer.allocateDirect(256); CharsetDecoder rbufDecoder = Charset.forName("UTF-8").newDecoder(); StringBuilder response = new StringBuilder(); int ops = SelectionKey.OP_WRITE | SelectionKey.OP_READ; if (this.channel.isConnectionPending()) { ops = ops | SelectionKey.OP_CONNECT; } Selector selector = Selector.open(); try { this.channel.register(selector, ops); while (true) { if (0 < selector.select(Client.POLLS_INTERVAL * 1000)) { Iterator keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = (SelectionKey) keys.next(); SocketChannel ch = (SocketChannel) key.channel(); if (key.isConnectable()) { // Just connected ch.finishConnect(); } if (key.isReadable() && !sbuf.hasRemaining()) { // Receiving the response while (0 < ch.read(rbuf)) { rbuf.flip(); response.append(rbufDecoder.decode(rbuf).toString()); } if (2 <= response.length() && response .substring(response.length() - 2, response.length()) .equals(SocketClient.TERMINATOR)) { response.setLength(response.length() - 2); return response.toString(); } else if (0 == response.length()) { throw new IOException("Connection lost"); } } if (key.isWritable() && sbuf.hasRemaining()) { // Sending the request while (0 < ch.write(sbuf) && sbuf.hasRemaining()) { // } } keys.remove(); } } } } catch (java.lang.Exception e) { throw new IOException("API communication failed: " + e.toString()); } finally { selector.close(); } }