List of usage examples for java.nio.channels AsynchronousSocketChannel open
public static AsynchronousSocketChannel open() throws IOException
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();// w ww .j a v a 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:Main.java
public static void main(String[] args) throws Exception { AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(); SocketAddress serverAddr = new InetSocketAddress("localhost", 8989); Future<Void> result = channel.connect(serverAddr); result.get();/*from w w w . j ava2 s . co m*/ System.out.println("Connected"); Attachment attach = new Attachment(); attach.channel = channel; attach.buffer = ByteBuffer.allocate(2048); attach.isRead = false; attach.mainThread = Thread.currentThread(); Charset cs = Charset.forName("UTF-8"); String msg = "Hello"; byte[] data = msg.getBytes(cs); attach.buffer.put(data); attach.buffer.flip(); ReadWriteHandler readWriteHandler = new ReadWriteHandler(); channel.write(attach.buffer, attach, readWriteHandler); attach.mainThread.join(); }
From source file:Test.java
private static void clientStart() { try {//www . j a va 2 s . co m InetSocketAddress hostAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 2583); AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open(); Future<Void> connectFuture = clientSocketChannel.connect(hostAddress); connectFuture.get(); // Wait until connection is done. OutputStream os = Channels.newOutputStream(clientSocketChannel); ObjectOutputStream oos = new ObjectOutputStream(os); for (int i = 0; i < 5; i++) { oos.writeObject("Look at me " + i); Thread.sleep(1000); } oos.writeObject("EOF"); oos.close(); clientSocketChannel.close(); } catch (Exception e) { e.printStackTrace(); } }