2 years ago

#4756

test-img

Nihal Shahria

Client does not receive message after receiving file from server via Socket

Here server and client can initially send and receive messages from each other. However, when the server sends a file, the client does not receive any message from the server after receiving the file. So at first, I tried to close the streams after sending and receiving file and reset those streams, but that doesn't work. I think maybe my stream declarations have a problem.

Note: server and client both send messages via terminal/console.

Server code:

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

/**
 *
 * @author nihalshahria
 */
public class ServerNoUi {

    ServerSocket server;
    Socket socket;
    final int port = 6666;
    DataInputStream in;
    BufferedReader inConsole;
    DataOutputStream out;

    public void start() throws IOException {
        server = new ServerSocket(port);
        socket = server.accept();
        String userName = System.getProperty("user.name");
        String folderPath = "/home/" + userName + "/SocketApp/Server/"; //folderPath to save incoming files
        mkDir(folderPath);  //create new folder according to folder path
        
        // streams initializations
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());
        inConsole = new BufferedReader(new InputStreamReader(System.in));
        /////////////////////////
        
        // Message send
        new Thread(() -> {
            while (true) {
                try {
                    String msgOut = inConsole.readLine();   //read input from terminal
                    String[] args = msgOut.split(" ", 2);
                    // if(msgOut starts with "-f ", that means next part of the msg will contain path of the file)
                    
                    if ("-f".equals(args[0]) && args.length == 2) { 
                        String path = args[1];
                        System.out.println(path);
                        File file = new File(path);
                        if (file.exists()) {
                            System.out.println("Sent " + file.getPath());
                            out.writeUTF("-f " + file.getName());
                            
                            // send file
                            int count;
                            byte[] buffer = new byte[65536];
                            InputStream fileIn;
                            try {
                                fileIn = new FileInputStream(file);
                                OutputStream fileOut = socket.getOutputStream();
                                while ((count = fileIn.read(buffer)) > 0) {
                                    fileOut.write(buffer, 0, count);
                                }
                                System.out.println("file sent");
//                                    fileOut.close();
//                                    fileIn.close();
//                                    restStreams();
                                try {
                                    out = new DataOutputStream(socket.getOutputStream());
                                } catch (IOException e) {
                                    System.out.println(e.getMessage());
                                }
                            } catch (IOException e) {
                                System.out.println(e.getMessage());
                            }
                            //////////////////////////
                            
                        } else {
                            System.out.println("File doesn't exist");
                        }
                    } else {
                        
                        // send message
                        System.out.println("From Server: " + msgOut);
                        out.writeUTF(msgOut);
                        ///////////////////
                        
                    }

                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }).start();

        // Message receive
        new Thread(() -> {
            while (true) {
                try {
                    String msgIn = in.readUTF();
                    System.out.println("From Client: " + msgIn);
                    
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }).start();
        /////////////////////

    }

    private static boolean mkDir(String name) {
        File dir = new File(name);
        if (dir.exists()) {
            return false;
        }
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) throws IOException {
        new ServerNoUi().start();
    }
}

Client code:

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

/**
 *
 * @author nihalshahria
 */
public class ClientNoUi {

    Socket socket;
    DataInputStream in;
    BufferedReader inConsole;
    DataOutputStream out;
    final int port = 6666;
    String folderPath;

    public void start() throws IOException {
        socket = new Socket("localhost", port);
        String userName = System.getProperty("user.name");
        folderPath = "/home/" + userName + "/SocketApp/Client/"; //folderPath to save incoming files
        mkDir(folderPath);   //create new folder according to folder path

        // streams initializations
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());
        inConsole = new BufferedReader(new InputStreamReader(System.in));
        /////////////////////////

        // Message send
        new Thread(() -> {
            while (true) {
                try {
                    String msgOut = inConsole.readLine();   //read input from terminal
                    String[] args = msgOut.split(" ", 2);
                    // if(msgOut starts with "-f ", that means next part of the msg will contain path of the file)

                    if ("-f".equals(args[0]) && args.length == 2) {
                        String path = args[1];
                        System.out.println(path);
                        File file = new File(path);
                        if (file.exists()) {
                            System.out.println("Sent " + file.getPath());
                            out.writeUTF("-f " + file.getName());

                        } else {
                            System.out.println("File doesn't exist");
                        }
                    } else {
                        System.out.println("From Client: " + msgOut);
                        out.writeUTF(msgOut);
                    }

                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }).start();

        // receive
        new Thread(() -> {
            while (true) {
                try {

                    String msgIn = in.readUTF();
                    String[] args = msgIn.split(" ", 2);
                    // if(msgIn starts with "-f ", that means next part of the msg will contain name of the file)
                    if ("-f".equals(args[0]) && args.length == 2) {

                        //file receive
                        InputStream fileIn = null;
                        OutputStream fileOut = null;
                        File file = new File(folderPath + args[1]);
                        try {
                            fileIn = socket.getInputStream();
                            fileOut = new FileOutputStream(file);
                            int count;
                            byte[] buffer = new byte[65536];
                            while ((count = fileIn.read(buffer)) > 0) {
                                fileOut.write(buffer, 0, count);
                            }
//                            fileIn.close();
//                            fileOut.close();
//                            System.out.println(file.getName() + " received");
//                            System.out.println("file saved in " + file.getAbsolutePath());
                            try {
                                in = new DataInputStream(socket.getInputStream());

                            } catch (Exception e) {
                                System.out.println("in " + e.getMessage());
                            }
//                            restStreams();            F
                            continue;
                            //////////////////////

                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                    System.out.println("From Server: " + msgIn);

                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }).start();

    }

    private static boolean mkDir(String name) {
        File dir = new File(name);
        if (dir.exists()) {
            return false;
        }
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) throws IOException {
        new ClientNoUi().start();
    }

}

java

file

sockets

inputstream

outputstream

0 Answers

Your Answer

Accepted video resources