package fr.upem.net.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class IterativeLongSumServer {
  
  private final ServerSocketChannel serverSocketChannel;
  
  public IterativeLongSumServer(int port) throws IOException {
    serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress(port));
    System.out.println(this.getClass().getName() 
        + " bound on " + serverSocketChannel.getLocalAddress());
  }
  
  public void launch() throws IOException {
    while(!Thread.interrupted()) {
      SocketChannel client = serverSocketChannel.accept();
      System.out.println("Connection accepted from " + client.getRemoteAddress());
      try {
        serve(client);
      } catch (IOException ioe) {
        System.out.println("I/O Error while communicating with client... ");
        ioe.printStackTrace();
      } catch (InterruptedException ie) {
        System.out.println("Server interrupted... ");
        ie.printStackTrace();
        break;
      } finally {
        silentlyClose(client);
      }
    }
  }
  
  private void serve(SocketChannel sc) throws IOException, InterruptedException {
    // TODO
  }
  
  private void silentlyClose(SocketChannel sc) {
    if (sc != null) {
      try {
        sc.close();
      } catch (IOException e) {
        // Do nothing
      }
    }
  }
  
  public static void main(String[] args) throws NumberFormatException, IOException {
    IterativeLongSumServer server = new IterativeLongSumServer(Integer.parseInt(args[0]));
    server.launch();
  }
}