编写异步客户端(基于CompletionHandler)
import java.io.IOException;/**时代Java公众号**/ import java.net.InetSocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Random; import java.util.concurrent.ExecutionException; public class Main { public static void main(String[] args) { try (AsynchronousSocketChannel asyncChannel = AsynchronousSocketChannel .open()) { if (asyncChannel.isOpen()) { asyncChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024); asyncChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024); asyncChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); asyncChannel.connect(new InetSocketAddress("127.0.0.1", 5555), null, /* from nowjava */ new CompletionHandler<Void, Void>() { ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !" .getBytes()); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); ByteBuffer randomBuffer; Charset charset = Charset.defaultCharset(); CharsetDecoder decoder = charset.newDecoder(); @Override public void completed(Void result, Void attachment) { try { System.out.println("Successfully connected at: " + asyncChannel.getRemoteAddress()); asyncChannel.write(helloBuffer).get(); while (asyncChannel.read(buffer).get() != -1) { buffer.flip(); CharBuffer charBuffer = decoder.decode(buffer); System.out.println(charBuffer.toString()); if (buffer.hasRemaining()) { buffer.compact(); } else { buffer.clear(); } asyncChannel.write(ByteBuffer.wrap("test".getBytes())).get(); } } catch (IOException | InterruptedException | ExecutionException ex) { System.err.println(ex); } finally { try { asyncChannel.close(); } catch (IOException ex) { System.err.println(ex); } } } @Override