Select Git revision
DStore.java
DStore.java 3.44 KiB
import java.io.*;
import java.net.*;
public class DStore {
private static String fileFolder;
private static int timeout;
public static void main(String[] args) {
//Take arguments from command line
int port = Integer.parseInt(args[0]);
int cPort = Integer.parseInt(args[1]);
timeout = Integer.parseInt(args[2]);
fileFolder = args[3];
//TODO Make connection with controller & listen to send acknowledgments
//Create socket to listen for store, load & remove requests
try{
//Create server socket to listen for connections
ServerSocket ss = new ServerSocket(port);
//Listen for connections
for(;;){
try{
//Accept connection & take inputs
Socket client = ss.accept();
InputStream in = client.getInputStream();
byte[] buf = new byte[1000];
int bufLen = in.read(buf);
String firstBuffer = new String(buf,0,bufLen);
//Make output stream returning to client
OutputStream out = client.getOutputStream();
//Get command (text before first space)
int firstSpace = firstBuffer.indexOf(" ");
String command = firstBuffer.substring(0,firstSpace);
//Get file name (text between first and second space)
int secondSpace = firstBuffer.indexOf(" ",firstSpace+1);
String fileName = firstBuffer.substring(firstSpace,secondSpace);
//Get file size (text after third space)
int thirdSpace = firstBuffer.indexOf(" ",secondSpace+1);
String fileSize = firstBuffer.substring(secondSpace,thirdSpace);
//If command = store, load or remove
switch (command) {
case "STORE" -> storeFile(in,out,fileName);
case "LOAD" -> loadFile(in,out,fileName);
case "REMOVE" -> removeFile(in,out,fileName);
}
//Close everything after use
in.close();
out.close();
client.close();
}catch (Exception e){
System.out.println("error "+e);
}
}
}catch (Exception e){
System.out.println("error "+e);
}
}
private static void storeFile(InputStream in, OutputStream out, String fileName) {
try {
//Send ACK to client
out.write("ACK".getBytes());
//Prepare new buffer for more data
byte[] buf = new byte[1000];
int bufLen;
//Prepare to write to file
File outputFile = new File(fileFolder + fileName);
FileOutputStream fileOutput = new FileOutputStream(outputFile);
//Wait for receipt of new data
while((bufLen = in.read(buf)) != -1) {
fileOutput.write(buf,0,bufLen);
}
//Close file output
fileOutput.close();
}catch (Exception e){
System.out.println("error "+e);
}
}
private static void loadFile(InputStream in, OutputStream out, String fileName) {
}
private static void removeFile(InputStream in, OutputStream out, String fileName) {
}
}