2

How can I send the file listing to client from server using Socket programming. I have used DataOutputStream and PrintWriter, both returns only one file name to Client. I know there is some problem in '\n'. But unable to solve it. Awaiting experts advice ... Thank you.

Client

switch (choice) {

.......

  case 2: // for viewing files in the client's directory
  Socket mysocket = new Socket("localhost", 6103);
  String user_name = username;
  DataOutputStream outToServer2= new DataOutputStream(mysocket.getOutputStream());
  outToServer2.writeBytes(user_name + '\n');
  BufferedReader inFromServer2 = new BufferedReader(newInputStreamReader(mysocket.getInputStream()));
  String list = inFromServer2.readLine();
  System.out.println("FROM SERVER - LIST OF FILES:" + list);

  break;

}

.......

Server

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

class DirList
{
   public static void main(String argv[]) throws Exception
      {
         String clientSentence;
         String capitalizedSentence;
         ServerSocket welcomeSocket = new ServerSocket(6103);

         while(true)
         {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
            clientSentence = inFromClient.readLine();
            System.out.println("Received view files request from user: " + clientSentence);
            String path = "/home/user/Files/";
            String userdir = path + clientSentence;
            String text="";
            String capitalizedSentence1;
            File f = new File(userdir);
                File[] listOfFiles = f.listFiles();
                for (int j = 0; j < listOfFiles.length; j++) {
                        if (listOfFiles[j].isFile()) {
                                text = listOfFiles[j].getName();
                                outToClient.println(text);
                                System.out.print(text+' ');

                   }
                }


         }
      }
}
highlander141
  • 1,683
  • 3
  • 23
  • 48

2 Answers2

3

You need to flush the output from your server:

outToClient.flush();

Also, in your client, you need to place the read in a loop to consume all the output:

String line = null;
while ((line = inFromServer2.readLine()) != null) {
   System.out.println(line);
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

Try using "\r\n". It might solve your problem.

conectionist
  • 2,694
  • 6
  • 28
  • 50