|
| 1 | +package com.baeldung.java.nio2.async; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.net.InetSocketAddress; |
| 6 | +import java.nio.ByteBuffer; |
| 7 | +import java.nio.channels.AsynchronousServerSocketChannel; |
| 8 | +import java.nio.channels.AsynchronousSocketChannel; |
| 9 | +import java.util.concurrent.ExecutionException; |
| 10 | +import java.util.concurrent.Future; |
| 11 | + |
| 12 | +public class AsyncEchoServer { |
| 13 | + private AsynchronousServerSocketChannel serverChannel; |
| 14 | + private Future<AsynchronousSocketChannel> acceptResult; |
| 15 | + private AsynchronousSocketChannel clientChannel; |
| 16 | + |
| 17 | + public AsyncEchoServer() { |
| 18 | + try { |
| 19 | + serverChannel = AsynchronousServerSocketChannel.open(); |
| 20 | + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); |
| 21 | + serverChannel.bind(hostAddress); |
| 22 | + acceptResult = serverChannel.accept(); |
| 23 | + } catch (IOException e) { |
| 24 | + e.printStackTrace(); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public void runServer() { |
| 29 | + try { |
| 30 | + clientChannel = acceptResult.get(); |
| 31 | + if ((clientChannel != null) && (clientChannel.isOpen())) { |
| 32 | + while (true) { |
| 33 | + |
| 34 | + ByteBuffer buffer = ByteBuffer.allocate(32); |
| 35 | + Future<Integer> readResult = clientChannel.read(buffer); |
| 36 | + |
| 37 | + while (!readResult.isDone()) { |
| 38 | + // do nothing |
| 39 | + } |
| 40 | + |
| 41 | + buffer.flip(); |
| 42 | + String message = new String(buffer.array()).trim(); |
| 43 | + if (message.equals("bye")) { |
| 44 | + break; // while loop |
| 45 | + } |
| 46 | + buffer = ByteBuffer.wrap(new String(message).getBytes()); |
| 47 | + Future<Integer> writeResult = clientChannel.write(buffer); |
| 48 | + while (!writeResult.isDone()) { |
| 49 | + // do nothing |
| 50 | + } |
| 51 | + buffer.clear(); |
| 52 | + |
| 53 | + } // while() |
| 54 | + |
| 55 | + clientChannel.close(); |
| 56 | + serverChannel.close(); |
| 57 | + |
| 58 | + } |
| 59 | + } catch (InterruptedException | ExecutionException | IOException e) { |
| 60 | + e.printStackTrace(); |
| 61 | + } |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + public static void main(String[] args) { |
| 66 | + AsyncEchoServer server = new AsyncEchoServer(); |
| 67 | + server.runServer(); |
| 68 | + } |
| 69 | + public static Process start() throws IOException, InterruptedException { |
| 70 | + String javaHome = System.getProperty("java.home"); |
| 71 | + String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; |
| 72 | + String classpath = System.getProperty("java.class.path"); |
| 73 | + String className = AsyncEchoServer.class.getCanonicalName(); |
| 74 | + |
| 75 | + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); |
| 76 | + |
| 77 | + return builder.start(); |
| 78 | + } |
| 79 | +} |
0 commit comments