简体   繁体   中英

Client/Server in java : Program gets stuck upon input of second file name

I am developing code to send multiple file names to server side and then making sure server recieves those contents and writes it to a file in its own folder. Its working well when I type first file name but when I type second file name the code kind of gets stuck.

Here is my client code:-

package fileTransfer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient {

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

    try {
        Socket clientSock=new Socket("localhost",8888);

        //to read from server
        BufferedReader br=new BufferedReader(new  InputStreamReader(clientSock.getInputStream())); //to read

        //to write to server
        PrintWriter pw=new PrintWriter(clientSock.getOutputStream(), true); 

        //for user input
        BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
        BufferedReader fileContent=null;
        String str=null;
        String fileContentLine=null;
        while(true){
            if((str=br.readLine()).contains("file name")) //recieve echo from server
                System.out.println(str);


            str=userIn.readLine(); //read user input
            fileContent=new BufferedReader(new FileReader(str));
            pw.println(str);
            while((fileContentLine=fileContent.readLine()) != null){
                pw.println(fileContentLine);
            }

            while((str=br.readLine())!=null)
                System.out.println(str);

            pw.flush();

        }

    }catch(IOException e){
        e.printStackTrace();
    }


}

}

And here is my server code

package fileTransfer;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {

 public static void main(String[] args){
    try {
        ServerSocket serverSock=new ServerSocket(8888);
        System.out.println("Waiting for client");
        Socket connectFromClient=serverSock.accept();

        File file=null;
        //reading data from client
        BufferedReader input=new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));

        //will write back to client
        PrintWriter pr=new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));

        PrintWriter writeToFile=null;
        //sending following statements to client
        pr.println("Connection established with server! Give a file name");
        pr.flush();

        String response;

        while(true){

            while((response=input.readLine()) != null)
            {
            if(response==null)
                break;
            else{

            System.out.println(response);
            if(response.contains(".txt")){

                //file=new File("FromClient.txt");
                  file=new File("FromClient"+response);
                if(!file.exists())
                    file.createNewFile();
                writeToFile=new PrintWriter(file);
            }
            else{

                //writeToFile=new PrintWriter(file);
                writeToFile.println(response);
            }

            pr.println("Echo from server -> " + response);

            //System.out.println("Adding these contents to a file");
            writeToFile.flush();
            pr.flush();
            }
            }
        }


    } catch (IOException e) {
        e.printStackTrace();
    }


}

}

It´s getting stuck in the client in this lines:

 while ((str = br.readLine()) != null) {
     System.out.println(str);
 }

Waiting for more server lines.

You have to tell the client when to stop from reading file data from socket stream and jump for the next file. For instance you can send before the content of the file the number of bytes you are going to transfer, you read that number of bytes from the stream and then go for the next file.

I post this modifications of your code as an example, as the idea I want to express. First I get the total linenumber of the file (I suppose text file), and I send it to server, which knows exactly how many lines to read before jumping to next file. It can be changed to use the total size of the file in bytes, for instance. This code is no 100% correct, it works, take it as an example.

Client:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;

    public class EchoClient {

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

            try {
                final Socket clientSock = new Socket("localhost", 8888);

                // to read from server
                final BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); // to
                // read

                // to write to server
                final PrintWriter pw = new PrintWriter(clientSock.getOutputStream(), true);

                // for user input
                final BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
                BufferedReader fileContent = null;
                String str = null;
                String fileContentLine = null;
                while (true) {
                    System.out.println("Print filename");
                    str = userIn.readLine(); // read user input
                    fileContent = new BufferedReader(new FileReader(str));
                    pw.println(str);
                    // first count the line number:
                    int lineno = 0;
                    while ((fileContentLine = fileContent.readLine()) != null) {
                        lineno++;
                    }
                    fileContent.close();
                    //
                    fileContent = new BufferedReader(new FileReader(str));
                    pw.println(String.valueOf(lineno));
                    while ((fileContentLine = fileContent.readLine()) != null) {
                        pw.println(fileContentLine);
                    }

                    for (int i = 0; i < lineno; i++) {
                        str = br.readLine();
                        System.out.println(str);
                    }

                    pw.flush();

                }

            } catch (final IOException e) {
                e.printStackTrace();
            }

        }
    }

Server:

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class EchoServer {

        public static void main(final String[] args) {
            try {
                final ServerSocket serverSock = new ServerSocket(8888);
                System.out.println("Waiting for client");
                final Socket connectFromClient = serverSock.accept();

                File file = null;
                // reading data from client
                final BufferedReader input = new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));

                // will write back to client
                final PrintWriter pr = new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));

                PrintWriter writeToFile = null;
                // sending following statements to client
                pr.println("Connection established with server! Give a file name");
                pr.flush();

                String response;

                while (true) {
                    final String fileName = input.readLine();
                    file = new File("FromClient" + fileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    writeToFile = new PrintWriter(file);
                    final String sLineNo = input.readLine();
                    final int lineno = Integer.parseInt(sLineNo);
                    for (int i = 0; i < lineno; i++) {
                        response = input.readLine();
                        System.out.println(response);

                        // writeToFile=new PrintWriter(file);
                        writeToFile.println(response);

                        pr.println("Echo from server -> " + response);

                        // System.out.println("Adding these contents to a file");
                        writeToFile.flush();
                        pr.flush();
                    }
                    writeToFile.close();
                }

            } catch (final IOException e) {
                e.printStackTrace();
            }

        }
    }

I Hope to be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM