ServerSocket serverSocket = new ServerSocket(Client.PORT);
//Make the server continually accept file transfers
while(true){
socket = serverSocket.accept();
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
FileOutputStream fileWrite = null;
byte [] buffer = new byte[Client.BUFFER_SIZE];
//First get file name
Object o = in.readObject();
if(o instanceof String){
// use the string as the files name
fileWrite = new FileOutputStream("downloads/" + o.toString());
}
else{
throw new Exception("something has gone terribly wrong");
}
Integer bytesRead = 0;
do {
o = in.readObject();
//Get the number of bytes in this wave
if(!(o instanceof Integer)){
throw new Exception("something has gone Very very bad");
}
bytesRead = (Integer)o;
o = in.readObject();
if(!(o instanceof byte[])){
throw new Exception("You messed up, and you did it bad!");
}
buffer = (byte[])o;
//Write data to output file.
fileWrite.write(buffer,0,bytesRead);
} while (bytesRead == Client.BUFFER_SIZE);
fileWrite.close();
in.close();
out.close();
}