#custom ftp server

1 messages · Page 1 of 1 (latest)

stone trellis
#

So, i am creating a FTP server, that works with a SERVER.java and Client.java..
When a client connects to the server, the server first reads a one-line command from the client.
The command can be:
• The string "LIST". In this case, the server responds by sending a list of names of all the
files that are available on the server.
• Or the command can be of the form "GET <filename>", where <filename> is a file name.
o The server checks whether the requested file exists.
o If so, it sends "OK" as a message to the client. Then it sends the contents of the
file and closes the connection.
o Otherwise, it sends a line beginning with the word "ERROR" to the client.
• The server can also respond with the message "unknown command" if the command it
reads is not one of the two possible legal commands,
For all the three cases, the server must return a thread ID (worker ID) to the client.
Your program should use a thread class to handle each request that the server receives. It should
not stop after handling one request; it should remain open and continue to accept new requests.

I am done with all this cases, but when I am typing GET Command in terminal my terminal get stucks...

This is the SERVER.java output

PS D:\Assignmensts\assignment 2> java -jar Server.jar
Server is listening on port 7210
Received command: LIST
Sent LIST response
Received command: LIST
Sent LIST response
Received command: GET test.txt
Sent OK response for file: test.txt

and This is the output of client.java

PS D:\Assignmensts\assignment 2> java Client 127.0.0.1 7210
Connecting to server 127.0.0.1:7210
---Connection Successful---
Received Worker ID: 21
Enter command (type 'exit' to close connection): LIST
Sending "LIST" to server
Server response:
test.txt
Enter command (type 'exit' to close connection): LIST
Sending "LIST" to server
Server response:
test.txt
Enter command (type 'exit' to close connection): GET test.txt 
Sending "GET test.txt" to server
File "test.txt" already exists. Do you want to overwrite it? (yes/no): yes


Here, after the File "test.txt" already exists. Do you want to overwrite it? (yes/no): yes line my terminal get stucks but the expected output is Download Successful...

i dont know, what part of my code is giving the issue, kindly help me please i request i am trying to fix from 4-5 hours... waiting for the response.

grave reefBOT
#

<@&987246883653156906> please have a look, thanks.

stone trellis
#

should i upload full code??

grave reefBOT
#

custom ftp server

#

Changed the title to custom ftp server.

frozen shuttle
stone trellis
#

okay wait i will paste the code

grave reefBOT
stone trellis
#

I hope you got the files

#

to run the files
you need to create the JAR file

#

javac Client.java
jar cfe Client.jar Client Client.class

javac Server.java
jar cfe Server.jar Server Server.class ClientThread.class

#

this are the commands

#

urgent help needed

#

Here it stucks

#

The Server responds but the client get stucked

boreal trout
stone trellis
#

oh yeah i forgot to tell you this

#

before compiling

#

you should change the path in the server.java

boreal trout
#

...or you could make so we wouldn't need to do this

stone trellis
#

sorry didnt understand this

#

private String directoryName = "C:\Users\Shind\OneDrive\Desktop\FTP";
instead of this drop your path

stone trellis
stone trellis
#

please can you try changing the path once

boreal trout
#

I won't run it anyway

#

There are several things that are bug at best

#

no idea if it is what is causing your problems

#

but here they are

#

also do you get any error ?

#

for example

#

and then you are closing it

#

it cannot worklike this

#

you must only create one scanner

#

and don't close it

stone trellis
#

there was a code provided to me
in that there was a comment
// Give the name of directory of the files at the server

stone trellis
boreal trout
stone trellis
#

yeah i got thayt

#

i tried every possible thing from my side still it shows the same

boreal trout
#

wdym

stone trellis
#

i am trying to fix this

boreal trout
#

@stone trellis data = in.read() is your code stuck here in the client ?

stone trellis
#

let me check

boreal trout
#

you guess ?

stone trellis
#

if i know this why i would be here ???

boreal trout
#

debug it please

#

put a breakpoint and see

#

or at least use prints

stone trellis
#

wait

#
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int data;
                while ((data = in.read()) != -1) {
                    writer.write(data);
                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }

grave reefBOT
stone trellis
#

this is the code

#

i used int but the file has words

#

so is this the error

#

see this

#

@boreal trout

boreal trout
stone trellis
#

HELLO WORLD

#

is it printing in bytes or bits?

#
private static void sendFile(String fileName, File directory, PrintWriter outgoing, BufferedReader incoming,
            Socket connection) {
        File file = new File(directory, fileName);

        if (file.exists() && file.isFile()) {
            try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file))) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                outgoing.println("OK");
                outgoing.flush();

                OutputStream outputStream = connection.getOutputStream();

                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();
                System.out.println("Sent OK response for file: " + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            outgoing.println("ERROR file not found");
            outgoing.flush();
            System.out.println("Sent ERROR file not found response for file: " + fileName);
        }
    }

This is a part of SERVER.JAVA

grave reefBOT
stone trellis
#

here i done Byte

boreal trout
#

ah I see

stone trellis
#

yep

boreal trout
#

but

#

you are testing against -1 to end the loop

#

but in the server

#

you never send -1 dont you ?

stone trellis
#

while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

boreal trout
#

yes you never send -1

stone trellis
#

yep

#

now?

boreal trout
#

now you need to fix it

stone trellis
#

how

boreal trout
#

how do you think ?

#

the client is waiting for -1

#

the server never send it

#

what's the problem ?

#

and how to fix it ?

stone trellis
#

mmm

#

idk

boreal trout
#

think a bit

stone trellis
#
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}

// Signal the end of the file transfer
outputStream.write(-1);
outputStream.flush();```
#

???

boreal trout
#

yes

stone trellis
#

does it fixed now?

#

should i try?

boreal trout
#

yes

stone trellis
#

should i also do the same in client?

#
int bytesRead;
while ((bytesRead = in.read()) != -1) {
    // Check for the end of the file signal
    if (bytesRead == -1) {
        break;
    }
    // Process the received data
    // ...
}
grave reefBOT
hoary kite
#

If you use java 9, there is also this method InputStream#transferTo(OutputStream out)

boreal trout
boreal trout
stone trellis
# boreal trout you are alreday doing it, why do you want to do it twice ?
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int bytesRead;
                while ((bytesRead = in.read()) != -1) {
                    writer.write(bytesRead);
                    System.out.println(bytesRead);
                    if (bytesRead == -1) {
                        break;
                    }
                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }
#

i mean for this

boreal trout
#

as I said

#

it doesn't makde any sense

#

why would you check the condition twice ?

hoary kite
boreal trout
stone trellis
#

lol yes sorrry sorry

hoary kite
#

alathreon is right, you are already checking if the input reads -1, no need to check again and then break the loop

boreal trout
#

@stone trellis you are basially doing

if(foo == -1) break;
if(foo == -1) break;

why do it twice ?

stone trellis
#

yes i got it

#

let me check now

#

it still stucks

boreal trout
#

show the code

stone trellis
#
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int data;
                while ((data = in.read()) != -1) {
                    writer.write(data);
                    // System.out.println(data);
                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }

Client.java

grave reefBOT
# stone trellis ```java try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {...

Detected code, here are some useful tools:

Formatted code
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
  int data;
  while ((data = in.read()) !=  - 1) {
    writer.write(data);
    // System.out.println(data);
  }
  System.out.println("File \"" + fileName + "\" downloaded successfully.");
} catch (IOException e) {
  e.printStackTrace();
  System.out.println("Error writing to file: " + e.getMessage());
}
}
else {
System.out.println("Server response:\n" + response);
}
}
stone trellis
#
private static void sendFile(String fileName, File directory, PrintWriter outgoing, BufferedReader incoming,
            Socket connection) {
        File file = new File(directory, fileName);

        if (file.exists() && file.isFile()) {
            try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file))) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                outgoing.println("OK");
                outgoing.flush();

                OutputStream outputStream = connection.getOutputStream();

                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                // Signal the end of the file transfer
                outputStream.write(-1);
                outputStream.flush();
                System.out.println("Sent OK response for file: " + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            outgoing.println("ERROR file not found");
            outgoing.flush();
            System.out.println("Sent ERROR file not found response for file: " + fileName);
        }
    }

Server.java

grave reefBOT
stone trellis
#

still it stucks after yes or no

#

but it only stucks for GET Command
LIST command is working fine

boreal trout
#

add back the print

stone trellis
#

it shows the same this

boreal trout
#

and see whats happening

stone trellis
#

thing

#

i did it

boreal trout
#

please show a screenshot

stone trellis
#

it prints the same thing

#

wait

#

see

#

@boreal trout

boreal trout
stone trellis
#

sorry

#

@boreal trout

#

can we join VC?

boreal trout
#

65533 🤔

#

no

hoary kite
stone trellis
boreal trout
stone trellis
boreal trout
#

I mean yea

#

but why

stone trellis
#
// Process the received data
    System.out.print((char) bytesRead); // assuming it's text data
}
#

i may try this

#
 try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int data;
                while ((data = in.read()) != -1) {
                    writer.write(data);
                    System.out.println(data);
                    // Check for the end of the file signal
                    if (data == -1) {
                        break;
                    }
                    // Process the received data
                    System.out.print((char) data); // assuming it's text data

                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }
grave reefBOT
stone trellis
#

i done this

#

this is the output

#

this are the assci numbers

#

ascii

#

i dont know why there is 65533
?

#

is it

#

the special character (65533) in the client. This character often represents the replacement character (�) and may indicate a problem with encoding or reading the file.

#

i just stack overflow

#

they say This character often represents the replacement character (�) and may indicate a problem with encoding or reading the file.

boreal trout
stone trellis
#

okay wait

boreal trout
stone trellis
boreal trout
stone trellis
boreal trout
stone trellis
#

yes

boreal trout
#

ah

stone trellis
#

i done this in the client

boreal trout
#

in the server

#

instead of sending -1

#

try to send 0

#

and see what the client get

#

just to test

stone trellis
#
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int data;
                while ((data = in.read()) != -1) {
                    writer.write(data);
                    System.out.println(data);
                    // Process the received data
                    System.out.print((char) data); // assuming it's text data

                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }

the latest client.java

grave reefBOT
stone trellis
#

and i also need to that inn client

#

isntit?

boreal trout
#

no

#

don't touch the client

stone trellis
#

oh wait

#

i done 0 in server as well as client

#

and this is the output

#

it worked and the file has been saved with text hello world
but there is another error now

boreal trout
#

please do what I say

stone trellis
#

okay wait

#

check

#

server side i changed

#

and client side i didnt

#

and it worked

#

but the same error of scnanner class

boreal trout
#

wait

#

it works now ?

#

what did you change ?

#

ah

#

no

stone trellis
#

what ??

#

i did it right

boreal trout
#

no

#

it's -1

#

not 0

stone trellis
#
PS D:\Assignmensts\assignment 2> java Client 127.0.0.1 7210
>>
Connecting to server 127.0.0.1:7210
---Connection Successful---
Received Worker ID: 25
Enter command (type 'exit' to close connection): GET test.txt
Sending "GET test.txt" to server
File "test.txt" already exists. Do you want to overwrite it? (yes/no): yes
File "test.txt" downloaded successfully.
Enter command (type 'exit' to close connection): Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.base/java.util.Scanner.nextLine(Scanner.java:1660)
        at Client.main(Client.java:30)
PS D:\Assignmensts\assignment 2> 
grave reefBOT
stone trellis
boreal trout
boreal trout
#

it's -1 in both

stone trellis
#

check it

stone trellis
#

also check the file names in the tab

#

okay??

#

only after this changes

boreal trout
#

I told you severeal times

stone trellis
#

wait

grave reefBOT
stone trellis
#

never closed any scanner

#

still the same error

boreal trout
# stone trellis still the same error

you are
try (Scanner userInput = new Scanner(System.in)) {
String overwriteChoice = userInput.nextLine().toLowerCase();

                if (!overwriteChoice.equals("yes")) {
                    System.out.println("Download canceled.");
                    return;
                }
            }
stone trellis
#

so what i should do

boreal trout
#

create only one scanner

#

and don't close it

#

like I said several times

stone trellis
#

yep so i need to remove the try catch>

#

?

boreal trout
#

yes and only create one scanner

stone trellis
#
private static void handleGetResponse(String command, String response, BufferedReader in, Scanner scanner) throws IOException {
        if (response.equals("OK")) {
            String fileName = command.substring(4).trim();
            File file = new File(fileName);

            if (file.exists()) {
                System.out.print("File \"" + fileName + "\" already exists. Do you want to overwrite it? (yes/no): ");
                String overwriteChoice = scanner.nextLine().toLowerCase();

                if (!overwriteChoice.equals("yes")) {
                    System.out.println("Download canceled.");
                    return;
                }
            }

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                int data;
                while ((data = in.read()) != -1) {
                    writer.write(data);
                }
                System.out.println("File \"" + fileName + "\" downloaded successfully.");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error writing to file: " + e.getMessage());
            }
        } else {
            System.out.println("Server response:\n" + response);
        }
    }
grave reefBOT
stone trellis
#

seee

#

like this/

#

?

boreal trout
#

yes

stone trellis
#

okay

#

wait let me chekc the output

#

done

#

done

#

yeahhhh

#

thanks a lot man

#

now see thisss

#
Connecting to server 127.0.0.1:7210
---Connection Successful---
Received Worker ID: 33
Enter command (type 'exit' to close connection): GET test.txt
Sending "GET test.txt" to server
File "test.txt" already exists. Do you want to overwrite it? (yes/no): yes    
File "test.txt" downloaded successfully.
Enter command (type 'exit' to close connection): GET text.txt
Sending "GET text.txt" to server
java.net.SocketException: An established connection was aborted by the software in your host machine
        at java.base/sun.nio.ch.SocketDispatcher.write0(Native Method)        
        at java.base/sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:54)
        at java.base/sun.nio.ch.NioSocketImpl.tryWrite(NioSocketImpl.java:394)
        at java.base/sun.nio.ch.NioSocketImpl.implWrite(NioSocketImpl.java:410)
        at java.base/sun.nio.ch.NioSocketImpl.write(NioSocketImpl.java:440)   
        at java.base/sun.nio.ch.NioSocketImpl$2.write(NioSocketImpl.java:819) 
        at java.base/java.net.Socket$SocketOutputStream.write(Socket.java:1195)
        at java.base/java.net.Socket$SocketOutputStream.write(Socket.java:1190)
        at java.base/java.io.DataOutputStream.writeBytes(DataOutputStream.java:277)
        at Client.main(Client.java:42)
PS D:\Assignmensts\assignment 2>
grave reefBOT
stone trellis
stone trellis
stone trellis
#

are you there?

#

@boreal trout

boreal trout
#

at ClientHandler.sendFile(Server.java:107)

stone trellis
#

what?

boreal trout
#

that's impossible

#

please show this line

stone trellis
#
private static void sendFile(String fileName, File directory, PrintWriter outgoing, BufferedReader incoming, Socket connection) {
    File file = new File(directory, fileName);

    if (file.exists() && file.isFile()) {
        try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buffer = new byte[1024];
            int bytesRead;

            outgoing.println("OK");
            outgoing.flush();

            OutputStream outputStream = connection.getOutputStream();

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // Signal the end of the file transfer
            outputStream.write(-1);
            outputStream.flush();
            System.out.println("Sent OK response for file: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        outgoing.println("ERROR file not found");
        outgoing.flush();
        System.out.println("Sent ERROR file not found response for file: " + fileName);
    }
}

ChatGPT suggested me this code

#

for the error

#

SHould i try this??

#

@boreal trout

#

hello

#

@boreal trout

stone trellis
boreal trout
#

sorry, ill go to sleep

#

but you have a weird out of bounds of index -1 Thinkfused

stone trellis
#

hmmm

#

bro its 5am in india

#

and i am still working

#

from 3pm now its 5am

#

It seems like there's an issue in the sendFile method of your ClientHandler class, specifically in this part:

while ((bytesRead = fileInputStream.read(buffer)) != 0) {
    outputStream.write(buffer, 0, bytesRead);
}

The condition (bytesRead = fileInputStream.read(buffer)) != 0 means that the loop will continue as long as bytesRead is not equal to 0. However, it should be checking for -1 instead of 0 to indicate the end of the file.

You can fix it by changing the condition to:

while ((bytesRead = fileInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}

This change ensures that the loop continues until the end of the file is reached, as read returns -1 when there is no more data to read. Update your sendFile method with this modification and see if it resolves the issue.

grave reefBOT
stone trellis
#

but with this the terminal get stucked

#

@boreal trout Thanks a lot that you helped me till now, thanks a lot man

#

now i also sleep a little then tomorrow i will try this again

#

good night

stone trellis
#

@boreal trout hey you there?

#

Anyone here?

stone trellis
#

any helper here ??

#

@cyan coral

#

please help mee

#

in this

#

i need your help

#

@stuck pagoda

#

@shrewd merlin

grave reefBOT
#

Of course! I'm here to help. What do you need assistance with?

stone trellis
#

?chat

grave reefBOT
# stone trellis ?chat

Looks like you attempted to use a command? Please note that we only use slash-commands on this server 🙂

Try starting your message with a forward-slash / and Discord should open a popup showing you all available commands.
A command might then look like /foo 👍

#

This exception is thrown when you try to access an element in an array or collection using an index that is outside the valid range of indices for that array or collection.

In this specific case, the exception message indicates that the range [0, 0 + -1) is out of bounds for an array with a length of 1024. This means that you are trying to access elements from index 0 to index -1, which is not a valid range.

To fix this issue, you need to make sure that the indices you use to access elements are within the valid range of indices for the array or collection. Double-check your code and ensure that you are using correct indices when accessing elements.

cyan coral
cyan coral
#

yeah and?

#

we all do this voluntarily, I am not forced to help you at all

#

instead you should try to get more interest into your question by improving it with more information, ...

stone trellis
#

@boreal trout HELLO BRO THANKS for helping me for everything

#

the code is runing well now

#

but there is a new issue regarding the Server Socket after completing one request of GET command
the server is automatically closed but the client side is still open
and when i put next command it thorws the error that the connection is aborted

#

@boreal troutSorry for distrubing you, but i felt you are a good person and wont be pissed of my questions

#

can you help me?

boreal trout
#

@stone trellis can you stop mentionning people please ?

stone trellis
#

yes

#

really sorry

#

can you help me?

boreal trout
#

Later

stone trellis
#

ohh okay