How to access a file in Client-Server architecture using Sockets in Java?

There’s a lot of irrelevant stuff in you question, it’s hard to see how your program works.

Here’s what should happen:

Client side:

  • User inputs a number
  • Client sends user’s number to server
  • Client receives response from server, and displays it

Server side:

  • Server listens for client connection
  • Server receives number from client
  • Server checks number against file bbd.txt
  • If number exists in file, return yes else return no

I have written some simple code to show you, excluding UI stuff:

Client.java:

public static void main(String[] args) {

  //set up server communication
  Socket clientSocket = new Socket("ip.address",1234);
  BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  PrintWriter out = new PrintWriter(socket.getOutputStream());


  //send PIN to server
  out.println("9.8.7.6");
  out.flush;

  //get response from server
  String response = in.readLine();
  System.out.println(response);

  in.close();
  out.close();
  clientSocket.close();
}

Server.java:

public static void main(String[] args) throws Exception {

  //Set up client communication
  ServerSocket server = new ServerSocket(1234);
  Socket socket = server.accept();      
  BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  PrintWriter out = new PrintWriter(socket.getOutputStream());

  //Listen for client requests:
  String request;
  while ((request = in.readLine()) != null) {

    //check PIN, send result
    boolean pinCorrect = checkPin(request);
    out.println(pinCorrect ? "yes" : "no");
    out.flush();
  }

  out.close();
  in.close();
  socket.close();
}

/**
 * Check if PIN is in bdd.txt
 */
private static boolean checkPin(String pin) {
  boolean result = false;
  File file = new File("bdd.txt");
  BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  String line;
  while ((line = in.readLine()) != null) {
    result |= (line.equals(pin));
  }
  in.close();
  return result;
}

Leave a Comment