/* 9P Protocol JAVA
 * P9P/server9P.java
 * Autor: Jaime Garzon (2006) jgarzon@gmail.com
 *
 * Implementacion especifica para J2ME.
 * 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 javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

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

public class server9PME extends server9P {

   public server9PME (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() {

      ServerSocketConnection srv= (ServerSocketConnection) null;
      SocketConnection client;
      threadConnection con;

      // Establece el servidor en el socket (espera 300 segundos)
      try {
         srv = (ServerSocketConnection) Connector.open("socket://:"+port);
      }
      catch (IOException e) {
         System.out.println( e );
      }

      // Ejecuta un bucle infinito de listen/accept
      while( true ) {
         try {
            client = (SocketConnection) srv.acceptAndOpen();

            if (now_con<=max_con) {
               con = new threadConnectionME(client, now_con);
               now_con ++;
               con.start();
            }
            else System.out.println("DEMASIADAS CONEXIONES...");
         }
         catch (IOException e) {
            System.out.println( e );
         }
      }
   }

   public class threadConnectionME extends threadConnection {
      private SocketConnection sk;

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

      }

      threadConnectionME (SocketConnection s, int id) {

         con_id=id;
         tfid=new fidtable(max_pet, root);
         sk=s;
         try {
            in = new  DataInputStream (sk.openDataInputStream());
            out = new DataOutputStream (sk.openDataOutputStream());
         }
         catch (IOException e) {
            System.out.println("[read-sz]" + e );
         }
      }
   }
}