This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.nio.ByteBuffer; | |
import java.nio.channels.AsynchronousSocketChannel; | |
import java.util.concurrent.ExecutionException; | |
public class AsynchronousSocketChannelClient { | |
public static void main(String[] args) { | |
try (AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();) { | |
channel.connect(new InetSocketAddress("localhost",5000)).get(); | |
channel.write(ByteBuffer.wrap("Hello".getBytes())).get(); | |
} catch (IOException | InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.nio.ByteBuffer; | |
import java.nio.channels.AsynchronousServerSocketChannel; | |
import java.nio.channels.AsynchronousSocketChannel; | |
import java.nio.charset.Charset; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.Future; | |
public class AsynchronousSocketChannelServer { | |
public static void main(String[] args) { | |
try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();) { | |
server.bind(new InetSocketAddress(5000)); | |
while (true) { | |
Future<AsynchronousSocketChannel> socket = server.accept(); | |
try (AsynchronousSocketChannel channel = socket.get();) { | |
ByteBuffer buffer = ByteBuffer.allocate(1024); | |
Future<Integer> result = channel.read(buffer); | |
Integer i = result.get(); | |
System.out.println("Read:" + i); | |
buffer.flip(); | |
System.out.println(new String(buffer.array())); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} catch (ExecutionException e) { | |
e.printStackTrace(); | |
} | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |