/* 9P Protocol JAVA
 * P9P/server9P.java
 * Autor: Jaime Garzon (2006) jgarzon@gmail.com
 *
 * Implementacion especifica para J2SE.
 * Esta clase implementa un servidor 9P. EL constructor es:
 * server9P (int maxcon, int maxfid, int p, boolean show, pfile f)
 *
 * El metodo process() ejecuta el servidor.
*/

package P9P;

import java.net.*;
import java.io.*;

import PFS.*;
import P9P.msg.*;
import P9P.rpcSrv.*;
import P9P.type.*;

public class server9PSE extends server9P {

   public server9PSE (int maxcon, int maxpet, int p, boolean show, pfile f) {
      showtraces=show;
      port=p;
      max_con=maxcon;
      now_con=0;
      max_pet=maxpet;
      root=f;
   }

   public void ejecutar() {

      ServerSocket srv = (ServerSocket)null;
      Socket s;
      threadConnection con;

      // Establece el servidor en el socket (espera 300 segundos)
      try {
         srv = new ServerSocket( port,300 );
      }
      catch (IOException e) {
         System.out.println( e );
      }

      // Ejecuta un bucle infinito de listen/accept
      while( true ) {
         try {
            s = srv.accept();
            if (now_con<=max_con) {
               con = new threadConnectionSE(s, now_con);
               now_con ++;
               con.start();
            }
            else printMsg("DEMASIADAS CONEXIONES...");
         }
         catch (IOException e) {
            System.out.println( e );
         }
      }
   }

   protected class threadConnectionSE extends threadConnection {
      protected Socket sk;

      public void closeConection() {
         try {
            sk.close();
            printMsg(con_id + " conexion cerrada...");
         }
         catch (IOException e) {
            System.out.println("[close]" + e );
         }
      }

      public threadConnectionSE (Socket s, int id) {
         con_id=id;
         tfid=new fidtable(max_pet, root);
         sk=s;
         try {
            in = new  DataInputStream (
               new BufferedInputStream (sk.getInputStream()));
            out = new DataOutputStream (sk.getOutputStream());
         }
         catch( IOException e ) {
            System.out.println("[read-sz]" + e );
         }
      }
   }
}