Example usage for java.nio.channels AsynchronousSocketChannel connect

List of usage examples for java.nio.channels AsynchronousSocketChannel connect

Introduction

In this page you can find the example usage for java.nio.channels AsynchronousSocketChannel connect.

Prototype

public abstract Future<Void> connect(SocketAddress remote);

Source Link

Document

Connects this channel.

Usage

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();// ww w . j a  v  a2 s.  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();// ww  w  .j  a va  2 s . c  o 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 {//from   www .j  a  v a2s .  c  o 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();
    }

}