I’m having to implement a basic file transfer system in Java, one that accepts commands from the client. Unfortunately, the class this was for has so far been more about networking concepts as opposed to code, so I am struggling a bit with the proper way to go about it. For any kind enough to help, if there’s a good guide or documentation somewhere as to how to do this I would be eternally grateful.
The current issue I am running into right now is that sometimes after I download or upload a file, it won’t let me put any more input and the client is essentially frozen. I believe it to be the server and client getting out of sync, but I have no clue where.
I’m aware that this code is an absolute mess so if there’s a guide already written or an example somewhere on how to properly do it you can just point me there instead of having to strain your eyes understanding all this spaghetti.
Client Side:
import java.io.*;
import java.net.*;
public class FTPClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int portNumber = 8888;
try (
Socket socket = new Socket(serverAddress, portNumber);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
// Handle server's initial welcome message or prompt
System.out.println(in.readLine()); // Read and display the "Please enter your username:" message
// Send username and handle response
String username = stdIn.readLine();
out.println(username);
System.out.println(in.readLine()); // Read and display the "Please enter your password:" message
// Send password and check for authentication
String password = stdIn.readLine();
out.println(password);
String serverResponse = in.readLine();
if (!serverResponse.startsWith("230")) {
System.out.println("Authentication failed: " + serverResponse);
return;
}
System.out.println("Authentication successful. Enter commands:");
// Handle commands
String userInput;
while ((userInput = stdIn.readLine()) != null) {
if (userInput.equalsIgnoreCase("QUIT")) {
out.println("QUIT");
System.out.println("Quitting...");
break;
} else if (userInput.equalsIgnoreCase("LIST")) {
out.println("LIST");
String response;
while (!(response = in.readLine()).equals("226 Directory listing complete")) {
System.out.println(response);
}
} else if (userInput.startsWith("DOWNLOAD ")) {
String fileName = userInput.substring(9); // Extracting filename from the command
receiveFile(fileName, socket);
} else if (userInput.startsWith("UPLOAD ")) {
String fileName = userInput.substring(7); // Extracting filename from the command
sendFile(fileName, socket, in);
} else {
System.out.println("Server response: " + in.readLine());
}
}
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverAddress);
} catch (IOException e) {
System.err.println("Error connecting to server: " + e.getMessage());
}
}
private static void sendFile(String fileName, Socket socket, BufferedReader in) {
try {
File file = new File(fileName);
if (file.exists()) {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("UPLOAD " + fileName);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
socket.getOutputStream().write(buffer, 0, bytesRead);
}
bis.close();
fis.close();
out.println("226 Transfer complete.");
System.out.println("File uploaded successfully");
} else {
System.out.println("File not found.");
}
} catch (IOException e) {
System.err.println("Error sending file: " + e.getMessage());
}
}
private static void receiveFile(String fileName, Socket socket) {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("DOWNLOAD " + fileName);
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
if (bytesRead < 4096) {
break;
}
}
bos.close();
fos.close();
System.out.println("File downloaded successfully");
} catch (IOException e) {
System.err.println("Error receiving file: " + e.getMessage());
}
}
}
And this is the server side:
import java.io.*;
import java.net.*;
import java.nio.file.*;
public class FTPServer {
private static final String ROOT_DIRECTORY = "C:\Users\pokem\Documents\CSCI 361\Server Side"; // Directory where files are stored
public static void main(String[] args) {
int portNumber = 8888;
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
System.out.println("Server started. Waiting for clients...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Handle each client in a separate thread
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
System.err.println("Error in server: " + e.getMessage());
}
}
static class ClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
private boolean authenticated = false;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
// Authentication
authenticate();
if (!authenticated) {
clientSocket.close();
return;
}
// Main loop for handling client commands
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.equalsIgnoreCase("QUIT")) {
System.out.println("Client disconnected: " + clientSocket);
break;
} else if (inputLine.equalsIgnoreCase("LIST")) {
listFiles();
} else if (inputLine.startsWith("DOWNLOAD ")) {
String fileName = inputLine.substring(9); // Extracting filename from the command
sendFile(fileName);
} else if (inputLine.startsWith("UPLOAD ")) {
String fileName = inputLine.substring(7); // Extracting filename from the command
receiveFile(fileName, in);
} else {
out.println("500 Invalid command.");
}
}
} catch (IOException e) {
System.err.println("Error handling client: " + e.getMessage());
}
}
private void authenticate() throws IOException {
out.println("Please enter your username:");
String username = in.readLine();
out.println("Please enter your password:");
String password = in.readLine();
authenticated = authenticateUser(username, password);
if (authenticated) {
out.println("230 Authentication successful. Welcome " + username + "!");
} else {
out.println("530 Authentication failed. Disconnecting...");
}
}
private boolean authenticateUser(String username, String password) {
// Simulated authentication - just a placeholder
return username.equals("admin") && password.equals("admin123");
}
private void listFiles() {
try {
File directory = new File(ROOT_DIRECTORY);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
out.println(file.getName());
}
}
}
out.println("226 Directory listing complete");
} catch (Exception e) {
out.println("550 Error listing directory");
}
}
private void sendFile(String fileName) {
try {
File file = new File(ROOT_DIRECTORY + File.separator + fileName);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
clientSocket.getOutputStream().write(buffer, 0, bytesRead);
}
bis.close();
fis.close();
System.out.println("File sent: " + fileName);
out.println("226 Transfer complete.");
} else {
out.println("550 File not found.");
}
} catch (IOException e) {
out.println("550 Error sending file");
}
}
private void receiveFile(String fileName, BufferedReader in) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = clientSocket.getInputStream().read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
if (new String(buffer, 0, bytesRead).trim().equals("226 Transfer complete.")) {
break;
}
}
bos.close();
fos.close();
System.out.println("File received: " + fileName);
} catch (IOException e) {
out.println("550 Error receiving file");
}
}
}
}
Jackson Allen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.