Java examples for Network:Socket Channel
Writing an Asynchronous Client (Based on CompletionHandler)
import java.io.IOException; 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()) {// w w w.j a v a 2 s .co m 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, 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 public void failed(Throwable exc, Void attachment) { throw new UnsupportedOperationException( "Connection cannot be established!"); } }); System.in.read(); } else { System.out.println("The asynchronous socket channel cannot be opened!"); } } catch (IOException ex) { System.err.println(ex); } } }