Java AsynchronousServerSocketChannel read object from client

Description

Java AsynchronousServerSocketChannel read object from client

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.Channels;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;

public class Main {

   InetSocketAddress hostAddress;

   private void start() throws IOException, ExecutionException, TimeoutException, InterruptedException {
      hostAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 2583);

      Thread serverThread = new Thread(new Runnable() {
         @Override//from  www. j  a  v  a  2 s  .  co m
         public void run() {
            serverStart();
         }
      });

      serverThread.start();

      Thread clientThread = new Thread(new Runnable() {
         @Override
         public void run() {
            clientStart();
         }
      });
      clientThread.start();

   }

   private void clientStart() {
      try {
         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();
      }

   }

   private void serverStart() {
      try {
         AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open().bind(hostAddress);
         Future<AsynchronousSocketChannel> serverFuture = serverSocketChannel.accept();

         AsynchronousSocketChannel clientConnection = serverFuture.get();
         InputStream connectionInputStream = Channels.newInputStream(clientConnection);
         ObjectInputStream ois = new ObjectInputStream(connectionInputStream);
         while (true) {
            Object object = ois.readObject();
            if (object.equals("EOF"))
               return;
            System.out.println("Received :" + object);
         }

      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args)
         throws IOException, ExecutionException, TimeoutException, InterruptedException {
      Main example = new Main();
      example.start();
   }

}



PreviousNext

Related