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

public class SNFIS {
  public static void main(String []a) {
    try {
      ServerSocket s = new ServerSocket(61234);
      while (true) {
        System.err.println("Le serveur attend une connexion");
        Socket service = s.accept();
        System.err.println("Un client vient d'arriver");
        InputStream lecture = service.getInputStream();
        BufferedReader bf = new BufferedReader(new InputStreamReader(lecture));
        OutputStream ecriture  = service.getOutputStream();
        PrintStream ps = new PrintStream(ecriture);
        String chaine = null;
        FileInputStream fis = null;
        boolean fin = false;
        while ( !fin && (chaine = bf.readLine()) != null ) {
          switch(chaine.charAt(0)) {
          case 'O':
            String fileName = chaine.substring(5);
            System.err.println("Un client souhaite ouvrir le fichier "+fileName);
            fileName = "repertoire/"+fileName;
            System.err.println("Sur le serveur il s'agit de "+fileName);
            fis = new FileInputStream(fileName);
            ps.println("OK");
            ps.flush();
            break;
          case 'R':
            System.err.println("Le client souhaite lire un octet");
            int b = fis.read();
            if (b!=-1)
              ps.println("OK "+(char)b);
            else
              ps.println("EOF");
            ps.flush();
            break;
          case 'C':
            System.err.println("Le client souhaite fermer le fichier");
            fis.close();
            fis = null;
            service.close();
            fin = true;
            break;
          }
        }
        service.close();
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}