List of usage examples for java.nio.channels AsynchronousSocketChannel write
@Override public abstract Future<Integer> write(ByteBuffer src);
From source file:Test.java
public static void main(String[] args) throws Exception { AsynchronousSocketChannel client = AsynchronousSocketChannel.open(); InetSocketAddress address = new InetSocketAddress("localhost", 5000); Future<Void> future = client.connect(address); System.out.println("Client: Waiting for the connection to complete"); future.get();//from ww w .j ava 2s. c o m String message = ""; while (!message.equals("quit")) { System.out.print("Enter a message: "); Scanner scanner = new Scanner(System.in); message = scanner.nextLine(); System.out.println("Client: Sending ..."); ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); System.out.println("Client: Message sent: " + new String(buffer.array())); client.write(buffer); } }
From source file:com.chicm.cmraft.rpc.PacketUtils.java
private static int writeRpc(AsynchronousSocketChannel channel, Message header, Message body, int totalSize) throws IOException, InterruptedException, ExecutionException { // writing total size so that server can read all request data in one read //LOG.debug("total size:" + totalSize); long t = System.currentTimeMillis(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); writeIntToStream(totalSize, bos);/* www. j av a2 s . c o m*/ header.writeDelimitedTo(bos); if (body != null) body.writeDelimitedTo(bos); bos.flush(); byte[] b = bos.toByteArray(); ByteBuffer buf = ByteBuffer.allocateDirect(totalSize + 4); buf.put(b); buf.flip(); channel.write(buf).get(); if (LOG.isTraceEnabled()) { LOG.trace("Write Rpc message to socket, takes " + (System.currentTimeMillis() - t) + " ms, size " + totalSize); LOG.trace("message:" + body); } return totalSize; }