mirror of
https://github.com/binlaab/nanofiles.git
synced 2026-07-01 12:17:21 +02:00
arreglado ping y empezado peerdl y dirdl
This commit is contained in:
@@ -246,6 +246,7 @@ public class NFController {
|
||||
case NFCommands.COM_FILELIST_PEER:
|
||||
case NFCommands.COM_DOWNLOAD_PEER:
|
||||
commandAllowed = (currentState == ONLINE);
|
||||
System.out.println("allowed = " + commandAllowed);
|
||||
if (!commandAllowed) {
|
||||
System.err.println("* Comando no permitido en estado OFFLINE. Haz un 'ping' primero.");
|
||||
}
|
||||
@@ -270,6 +271,7 @@ public class NFController {
|
||||
|
||||
switch (currentCommand) {
|
||||
case NFCommands.COM_PING:
|
||||
System.out.println("updateCurrentState ping");
|
||||
currentState = ONLINE;
|
||||
break;
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package es.um.redes.nanoFiles.logic;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.io.IOException;
|
||||
import es.um.redes.nanoFiles.tcp.client.NFConnector;
|
||||
import es.um.redes.nanoFiles.application.NanoFiles;
|
||||
@@ -157,12 +159,36 @@ public class NFControllerLogicP2P {
|
||||
// TODO: localizar peers con el hash solicitado (o uno concreto) y delegar en
|
||||
// downloadFileFromServers
|
||||
boolean success = false;
|
||||
|
||||
|
||||
|
||||
LinkedList<InetSocketAddress> peersWithFile = new LinkedList<>();
|
||||
Map<String, InetSocketAddress> peers = dirLogic.fetchPeerList();
|
||||
|
||||
LinkedList<InetSocketAddress> targets = new LinkedList<>();
|
||||
|
||||
/* if (targetPeerNickname == "*") { bloqueado de momento
|
||||
targets.addAll(peers.values());
|
||||
} else { */
|
||||
targets.add(peers.get(targetPeerNickname));
|
||||
// }
|
||||
|
||||
for (InetSocketAddress addr : targets) {
|
||||
try {
|
||||
NFConnector nfc = new NFConnector(addr);
|
||||
FileInfo[] peerFiles = nfc.getFileList();
|
||||
|
||||
// la longitud tiene que ser EXACTAMENTE 1, si es 0 no hay, si es > 1 es ambiguo
|
||||
// y si resulta que dos peers tienen un mismo subhash sin tener el mismo hash?
|
||||
// mando que no se ha podido descargar? comparo contra el hash del primero?
|
||||
FileInfo[] peerFilesFound = FileInfo.lookupHashSubstring(peerFiles, targetHashSubstring);
|
||||
if (peerFilesFound.length == 1) {
|
||||
peersWithFile.add(addr);
|
||||
}
|
||||
} catch (IOException e) { e.printStackTrace(); }
|
||||
}
|
||||
|
||||
success = downloadFileFromServers(peersWithFile.toArray(new InetSocketAddress[0]), targetHashSubstring);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Método para descargar un fichero del peer servidor de ficheros
|
||||
*
|
||||
@@ -180,10 +206,15 @@ public class NFControllerLogicP2P {
|
||||
// TODO: crear conectores TCP solo a los servidores que confirmen el hash
|
||||
// pedido, obtener nombre remoto, reservar nombre local sin colisiones, alternar
|
||||
// descarga de chunks y verificar hash final. Cerrar los sockets al terminar.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
NFConnector[] peerConns = new NFConnector[serverAddressList.length];
|
||||
|
||||
for (int i = 0; i < serverAddressList.length; i++) {
|
||||
try {
|
||||
NFConnector nfc = new NFConnector(serverAddressList[i]);
|
||||
peerConns[i] = nfc;
|
||||
} catch (IOException e) { e.printStackTrace(); }
|
||||
}
|
||||
return downloaded;
|
||||
}
|
||||
|
||||
@@ -207,10 +238,9 @@ public class NFControllerLogicP2P {
|
||||
/*
|
||||
* TODO: Devolver el puerto de escucha de nuestro servidor de ficheros
|
||||
*/
|
||||
|
||||
|
||||
|
||||
return NFServer.PORT;
|
||||
if (fileServer != null) {
|
||||
return fileServer.getServerSocket().getLocalPort();
|
||||
} else return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -99,10 +99,26 @@ public class NFConnector {
|
||||
} else { return null; }
|
||||
return filelist.toArray(new FileInfo[0]);
|
||||
} catch (IOException e) { e.printStackTrace(); return null; }
|
||||
|
||||
|
||||
}
|
||||
|
||||
public byte[] downloadChunk(String hash, int chunkNum) {
|
||||
try {
|
||||
PeerMessage msgOut = new PeerMessage(PeerMessageOps.OPCODE_REQUEST_PEER_DL);
|
||||
msgOut.setFileHash(hash);
|
||||
msgOut.setChunkNum(chunkNum);
|
||||
|
||||
msgOut.writeMessageToOutputStream(dos);
|
||||
|
||||
PeerMessage msgIn = PeerMessage.readMessageFromInputStream(dis);
|
||||
|
||||
if (msgIn.getOpcode() == PeerMessageOps.OPCODE_PEER_DL) {
|
||||
return msgIn.getFileData();
|
||||
}
|
||||
|
||||
} catch (IOException e) { e.printStackTrace(); }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public InetSocketAddress getServerAddr() {
|
||||
return serverAddr;
|
||||
|
||||
@@ -25,6 +25,7 @@ public class PeerMessage {
|
||||
private String filenameVal;
|
||||
|
||||
private byte[] fileData;
|
||||
private int chunkNum;
|
||||
|
||||
|
||||
|
||||
@@ -98,6 +99,14 @@ public class PeerMessage {
|
||||
public void setFileData(byte[] fileData) {
|
||||
this.fileData = fileData;
|
||||
}
|
||||
|
||||
public int getChunkNum() {
|
||||
return chunkNum;
|
||||
}
|
||||
|
||||
public void setChunkNum(int chunkNum) {
|
||||
this.chunkNum = chunkNum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Método de clase para parsear los campos de un mensaje y construir el objeto
|
||||
@@ -149,11 +158,14 @@ public class PeerMessage {
|
||||
}
|
||||
|
||||
case PeerMessageOps.OPCODE_REQUEST_PEER_DL: {
|
||||
int longitudSubHash = (int)dis.readByte();
|
||||
// buscar archivo supongo
|
||||
}
|
||||
case PeerMessageOps.OPCODE_PEER_DL: {
|
||||
int longitudSubHash = (int) dis.readByte();
|
||||
byte[] subHash = new byte[longitudSubHash];
|
||||
dis.readFully(subHash);
|
||||
break;
|
||||
// buscar archivo supongo
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -219,7 +219,7 @@ public class NFServer implements Runnable {
|
||||
|
||||
msgOut.setFileHash(archivo.fileHash);
|
||||
msgOut.setFileSize(archivo.fileSize);
|
||||
msgOut.setFilenameVal(archivo.fileName);
|
||||
msgOut.setFilenameVal(archivo.filePath + archivo.fileName);
|
||||
msgOut.setFilenameLong((byte)archivo.fileName.length());
|
||||
msgOut.setLast(false);
|
||||
if (i == archivos.length - 1) msgOut.setLast(true);
|
||||
|
||||
@@ -259,6 +259,7 @@ public class DirectoryConnector {
|
||||
byte[] resp = sendAndReceiveDatagrams(pingBytes);
|
||||
String respStr = new String(resp, 0, resp.length);
|
||||
DirMessage respPing = DirMessage.fromString(respStr);
|
||||
System.out.println("pingDir - " + respPing.getOperation());
|
||||
success = (respPing.getOperation().equals(DirMessageOps.OPERATION_PING_OK));
|
||||
|
||||
|
||||
@@ -355,9 +356,14 @@ public class DirectoryConnector {
|
||||
String filename = null;
|
||||
long filesize = -1;
|
||||
String filehash = null;
|
||||
|
||||
|
||||
|
||||
|
||||
FileInfo[] list = this.getFileList();
|
||||
FileInfo[] foundFile = FileInfo.lookupHashSubstring(list, hashSubstring);
|
||||
|
||||
// TODO: crear nuevo mensaje dirdl y requestdirdl
|
||||
// similar a un mensaje peerdl
|
||||
// pasarle hashSubstring a DirMessage y dejar que vaya desde ahí
|
||||
// implementar toda la lógica en DirMessage
|
||||
return new DownloadedFile(filename, filesize, fileData, filehash);
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,10 @@ public class DirMessage {
|
||||
public String getOperation() {
|
||||
return operation;
|
||||
}
|
||||
|
||||
public void setOperation(String op) {
|
||||
this.operation = op;
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO: (Boletín MensajesASCII) Crear métodos getter y setter para obtener los
|
||||
@@ -213,7 +217,7 @@ public class DirMessage {
|
||||
|
||||
for (int i = 0; i < archivos.length; i++) {
|
||||
String[] atributos = archivos[i].split(":");
|
||||
FileInfo archivo = new FileInfo(atributos[2], atributos[0], Long.parseLong(atributos[1]), null); // de momento no meto el path
|
||||
FileInfo archivo = new FileInfo(atributos[2], atributos[0], Long.parseLong(atributos[1]), atributos[3]); // de momento no meto el path
|
||||
listaArchivos[i] = archivo;
|
||||
}
|
||||
|
||||
@@ -280,7 +284,7 @@ public class DirMessage {
|
||||
sb.append(FIELDNAME_FILELIST + DELIMITER);
|
||||
for (int i = 0; i < fileList.length; i++) {
|
||||
FileInfo f = fileList[i];
|
||||
sb.append(f.fileName + ':' + f.fileSize + ':' + f.fileHash);
|
||||
sb.append(f.fileName + ':' + f.fileSize + ':' + f.fileHash + ':' + f.filePath);
|
||||
if (i < fileList.length - 1) {
|
||||
sb.append(','); // para evitar una coma al final
|
||||
}
|
||||
|
||||
@@ -226,13 +226,13 @@ public class NFDirectoryServer {
|
||||
* done: (Boletín MensajesASCII) Comprobamos si el protocolId del mensaje del
|
||||
* cliente coincide con el nuestro.
|
||||
*/
|
||||
msgToSend = new DirMessage(operation);
|
||||
String protocolId = receivedMsg.getProtocolId();
|
||||
System.out.println(protocolId.equals(NanoFiles.PROTOCOL_ID));
|
||||
if (protocolId.equals(NanoFiles.PROTOCOL_ID)) {
|
||||
operation = DirMessageOps.OPERATION_PING_OK;
|
||||
System.out.println("Tenemos el protocolo bien");
|
||||
msgToSend.setOperation(DirMessageOps.OPERATION_PING_OK);
|
||||
} else {
|
||||
operation = DirMessageOps.OPERATION_PING_BAD;
|
||||
msgToSend.setOperation(DirMessageOps.OPERATION_PING_BAD);
|
||||
}
|
||||
/*
|
||||
* done: (Boletín MensajesASCII) Construimos un mensaje de respuesta que indique
|
||||
|
||||
@@ -11,6 +11,7 @@ public class FileNameUtil {
|
||||
* añade sufijos .1, .2, etc. hasta encontrar un nombre libre.
|
||||
*/
|
||||
public static Path chooseAvailableName(String baseName) {
|
||||
System.out.println(baseName);
|
||||
Path path = Paths.get(baseName);
|
||||
int suffix = 1;
|
||||
while (Files.exists(path)) {
|
||||
|
||||
Reference in New Issue
Block a user