Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package example;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetSocketAddress;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.AsynchronousServerSocketChannel;
  7. import java.nio.channels.AsynchronousSocketChannel;
  8. import java.util.concurrent.ExecutionException;
  9. import java.util.concurrent.Future;
  10. import java.util.concurrent.TimeUnit;
  11. import java.util.concurrent.TimeoutException;
  12.  
  13. public class Server {
  14.     public static void main(String[] args) {
  15.         try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()) {
  16.             server.bind(new InetSocketAddress("127.0.0.1", 1234));
  17.             Future<AsynchronousSocketChannel> acceptCon = server.accept();
  18.             AsynchronousSocketChannel client = acceptCon.get(10, TimeUnit.SECONDS);
  19.             if ((client != null) && (client.isOpen())) {
  20.                 ByteBuffer buffer = ByteBuffer.allocate(1024);
  21.                 Future<Integer> readval = client.read(buffer);
  22.                 System.out.println("Received from client: " + new String(buffer.array()).trim());
  23.                 readval.get();
  24.                 buffer.flip();
  25.                 String str = "I'm fine. Thank you!";
  26.                 Future<Integer> writeVal = client.write(ByteBuffer.wrap(str.getBytes()));
  27.                 System.out.println("Writing back to client: " + str);
  28.                 writeVal.get();
  29.                 buffer.clear();
  30.                 client.close();
  31.             }
  32.         } catch (ExecutionException | InterruptedException | TimeoutException | IOException e) {
  33.             e.printStackTrace();
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement