/** * If we succeed to write everything in writeBuffer, client write is finished => invoke * writeCallback */ private void doWrite() { int written = 0; try { if (((SocketChannel) channel).isConnected()) { written = ((SocketChannel) channel).write(ByteBuffer.wrap(writeBuffer.toString().getBytes())); } } catch (IOException e) { logger.error("IOException during write: {}", e.getMessage()); invokeCloseCallback(); Closeables.closeQuietly(channel); } writeBuffer.delete(0, written); logger.debug("wrote: {} bytes", written); logger.debug("writeBuffer size: {}", writeBuffer.length()); if (writeBuffer.length() > 0) { IOLoop.INSTANCE.updateHandler(channel, interestOps |= SelectionKey.OP_WRITE); } else { IOLoop.INSTANCE.updateHandler(channel, interestOps &= ~SelectionKey.OP_WRITE); invokeWriteCallback(); } }
/** Should only be invoked by the IOLoop */ @Override public void handleRead(SelectionKey key) throws IOException { logger.debug("handle read..."); ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BYTEBUFFER_SIZE); int read = ((SocketChannel) key.channel()).read(buffer); if (read == -1) { // EOF reachedEOF = true; IOLoop.INSTANCE.updateHandler(channel, interestOps &= ~SelectionKey.OP_READ); return; } readBuffer.append(new String(buffer.array(), 0, buffer.position(), Charsets.ISO_8859_1)); logger.debug("readBuffer size: {}", readBuffer.length()); checkReadState(); }
/** * Connects to the given host port tuple and invokes the given callback when a successful * connection is established. */ public void connect(String host, int port, AsyncResult<Boolean> ccb) { IOLoop.INSTANCE.updateHandler(channel, interestOps |= SelectionKey.OP_CONNECT); connectCallback = ccb; if (channel instanceof SocketChannel) { try { ((SocketChannel) channel).connect(new InetSocketAddress(host, port)); } catch (IOException e) { logger.error("Failed to connect to: {}, message: {} ", host, e.getMessage()); invokeConnectFailureCallback(e); } catch (UnresolvedAddressException e) { logger.warn("Unresolvable host: {}", host); invokeConnectFailureCallback(e); } } }
/** Should only be invoked by the IOLoop */ @Override public void handleConnect(SelectionKey key) throws IOException { logger.debug("handle connect..."); SocketChannel sc = (SocketChannel) channel; if (sc.isConnectionPending()) { try { sc.finishConnect(); invokeConnectSuccessfulCallback(); interestOps &= ~SelectionKey.OP_CONNECT; IOLoop.INSTANCE.updateHandler(channel, interestOps |= SelectionKey.OP_READ); } catch (ConnectException e) { logger.warn("Connect failed: {}", e.getMessage()); invokeConnectFailureCallback(e); } } }