0

I am new to java. I am learning socket and thread programing by making a chat application where message sent from the client will be received by the server and the server will sent it to another client.

The server works like this. The 1st word of the string is the command and rest are arguments.

command to message Example: msg jony Hi!

This will send Hi! to client name jony. //

login tom tom123 // will login to tom using username "tom" and password "tom123"

Now I want to add file transfer. So one client can send file to another client. As far as I know I need to use DataInputStream for it. In that case how can i make the server differentiate between file and text in the following program? Or can i make it like "file jony c://abc.txt" to send abc.txt file to jony?

Edited: Looks like handleFile is called but then its nothing. (It works if hangle file is called at the start like handfleFile();

What am I doing wrong :(

Here is part of my Server code.

    private void handleClientSocket() throws IOException, InterruptedException, SQLException {
//        InputStream inputStream = clientSocket.getInputStream();
//        this.outputStream = clientSocket.getOutputStream();
//        DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
        this.outputStream = new DataOutputStream(clientSocket.getOutputStream());
        this.inputStream = new DataInputStream(clientSocket.getInputStream());

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        Connect(); //Connects to databse
//        handleFile();
        while ( (line = reader.readLine()) != null) {
            String[] tokens = StringUtils.split(line);
            if (tokens != null && tokens.length > 0) {
                String cmd = tokens[0];
                if ("quit".equalsIgnoreCase(cmd) || "logoff".equalsIgnoreCase(cmd)) {
                    handleLogOff();
                    break;
                } else if ("login".equalsIgnoreCase(cmd)) {
                    handleLogin(outputStream, tokens);
                } else if ("msg".equalsIgnoreCase(cmd)) {
                    String[] tokenMsg = StringUtils.split(line, null, 3);
                    handleMessage(tokenMsg);
                } else if ("join".equalsIgnoreCase(cmd)) {
                    handleJoin(tokens);
                } else if ("leave".equalsIgnoreCase(cmd)) {
                    handleLeave(tokens);
                } else if ("signup".equalsIgnoreCase(cmd)) {
                    handleSignUp(tokens);
                } else if ("create".equalsIgnoreCase(cmd)) {
                    handleCreateGroup(tokens);
                } else if ("sendFile".equalsIgnoreCase(cmd)) {
//                    inputStream.close();
                    handleFile();
                }

                else {
                    String msg = "Unknown command: " + cmd + "\n";
                    outputStream.write(msg.getBytes());
                }
            }
        }
    }

    private void handleFile (){
        System.out.println("File handler called");
        try {
            System.out.println("File handler called");
//            DataInputStream input = new DataInputStream(clientSocket.getInputStream());
            DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
            int fileNameLength = inputStream.readInt();
            System.out.println(fileNameLength);
            if (fileNameLength > 0) {
                byte[] fileNameBytes = new byte[fileNameLength];
                inputStream.readFully(fileNameBytes, 0, fileNameBytes.length);
                String fileName = new String(fileNameBytes);
                System.out.println(fileName);
                int fileContentLength = inputStream.readInt();
                System.out.println(fileContentLength);
                if (fileContentLength > 0) {
                    byte[] fileContentBytes = new byte[fileContentLength];
                    inputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
                    System.out.println(fileContentBytes);

//                    File fileToDownload = new File(fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream("D:\\bbb.txt");
                    fileOutputStream.write(fileContentBytes);
                    fileOutputStream.close();
                }
            }

Here is client code:

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        final File[] fileToSend = new File[1];
//        fileToSend[0] = "C:\\Users\\alvyi\\Downloads";
        File file = new File("D:\\aaa.txt");

        try {
            Socket socket = new Socket("localhost", 6000);
            DataInputStream inputStream = new DataInputStream(socket.getInputStream());

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        while(true){
            System.out.println("In the Loop");

            dataOutputStream.write("login alvy alvy\n".getBytes(StandardCharsets.UTF_8));
            dataOutputStream.write("sendFile\n".getBytes(StandardCharsets.UTF_8));

            FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath());
            String fileName = file.getName();
            // Convert the name of the file into an array of bytes to be sent to the server.
            byte[] fileNameBytes = fileName.getBytes();
            // Create a byte array the size of the file so don't send too little or too much data to the server.
            byte[] fileBytes = new byte[(int)file.length()];
            // Put the contents of the file into the array of bytes to be sent so these bytes can be sent to the server.
            fileInputStream.read(fileBytes);
            // Send the length of the name of the file so server knows when to stop reading.
            dataOutputStream.writeInt(50);
            dataOutputStream.writeInt(fileNameBytes.length);
            // Send the file name.
            dataOutputStream.write(fileNameBytes);
            // Send the length of the byte array so the server knows when to stop reading.
            dataOutputStream.writeInt(fileBytes.length);
            // Send the actual file.
            dataOutputStream.write(fileBytes);



            String echoString = scanner.nextLine();
        }
    //        System.out.println(inputStream.readLine());

     //       outputStream.write("sendFile".getBytes());



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



    }
}

1 Answers1

0

In that case how can i make the server differentiate between file and text in the following program? Or can i make it like "file jony c://abc.txt" to send abc.txt file to jony?

From a usability point of view it makes sense to make the send file command a separate command in your chat API. Therefore, the idea with adding a different command to do it with a descriptive name like file makes sense.

If we are to talk about the implementation of the API, then this is a standard problem with a standard solution.

Here is the code, which explains how to send the file over a socket.

Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17
  • Yes I did that but looks like its not doing anything. But if I call the method at the start (Currently commented) it works!!! My head hurts now :/ – Alvy Feroz Nov 09 '21 at 16:42
  • Why not call it at the start then ? – Arthur Klezovich Nov 09 '21 at 16:48
  • That would ruin the whole purpose. I want to sent the file only when the client sends command sendFile. If i use it at the start then I will need to send a file every time then can start doing other stuffs. I have updated the code. If possible kindly look at it :( – Alvy Feroz Nov 09 '21 at 16:55
  • Thanks man finally got it the BufferReader was causing all the issues. Using inputStream.readLine() fixed this issue. (Home it dont cause issue in the future lol) – Alvy Feroz Nov 09 '21 at 17:02
  • If my answer has helped you, please feel free to mark the answer as accepted and upvote – Arthur Klezovich Nov 09 '21 at 17:08