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

public class NFIS extends InputStream {
  Socket service;
  InputStream lecture;
  BufferedReader bf;
  OutputStream ecriture;
  PrintStream ps;
  public NFIS(String f) {
    try {
      service = new Socket("localhost",61234);
      lecture = service.getInputStream();
      bf = new BufferedReader(new InputStreamReader(lecture));
      ecriture  = service.getOutputStream();
      ps = new PrintStream(ecriture);
      ps.println("OPEN "+f);
      ps.flush();
      String s = bf.readLine();
      if (s.charAt(0)=='O') System.err.println("Fichier ouvert");
      else System.err.println("Raté");
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
  public int read() {
    try {
      ps.println("READ");
      ps.flush();
      String s = bf.readLine();
      if (s!=null && s.length()!=0) {
        switch (s.charAt(0)) {
        case 'O':
          byte []bb = s.getBytes();
          System.err.println("Bytes reçus "+bb.length);
          for (int i=0; i<bb.length; i++) System.err.println(i+" : "+(int)(bb[i]));
          char c = 0;
          System.err.println(s.length());
          if (s.length()<4) c = '\n';
          else c = s.charAt(3);
          System.err.println("J'ai recu le caractère "+c);
          return (int)c;
        case 'E':
          System.err.println("fin de fichier détectée");
          return -1;
        case 'B':
          break;
        }
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
    return 0;
  }
  public void close() {
    try {
      ps.println("CLOSE");
      ps.flush();
      service.close();
    } catch(Exception e) {
      e.printStackTrace();
    }

  }

  // Code utilisateur...
  public static void main(String []a) {
    try {
      InputStream is  = new NFIS("essai.txt");
      BufferedReader bf = new BufferedReader(new InputStreamReader(is));
      System.out.println("J'ai lu "+bf.readLine());
      is.close();
    } catch(Exception e) {
      e.printStackTrace();
    }

  }
}