mirror of
https://github.com/binlaab/nanofiles.git
synced 2026-07-01 18:26:30 +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_FILELIST_PEER:
|
||||||
case NFCommands.COM_DOWNLOAD_PEER:
|
case NFCommands.COM_DOWNLOAD_PEER:
|
||||||
commandAllowed = (currentState == ONLINE);
|
commandAllowed = (currentState == ONLINE);
|
||||||
|
System.out.println("allowed = " + commandAllowed);
|
||||||
if (!commandAllowed) {
|
if (!commandAllowed) {
|
||||||
System.err.println("* Comando no permitido en estado OFFLINE. Haz un 'ping' primero.");
|
System.err.println("* Comando no permitido en estado OFFLINE. Haz un 'ping' primero.");
|
||||||
}
|
}
|
||||||
@@ -270,6 +271,7 @@ public class NFController {
|
|||||||
|
|
||||||
switch (currentCommand) {
|
switch (currentCommand) {
|
||||||
case NFCommands.COM_PING:
|
case NFCommands.COM_PING:
|
||||||
|
System.out.println("updateCurrentState ping");
|
||||||
currentState = ONLINE;
|
currentState = ONLINE;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package es.um.redes.nanoFiles.logic;
|
|||||||
|
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.Map;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import es.um.redes.nanoFiles.tcp.client.NFConnector;
|
import es.um.redes.nanoFiles.tcp.client.NFConnector;
|
||||||
import es.um.redes.nanoFiles.application.NanoFiles;
|
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
|
// TODO: localizar peers con el hash solicitado (o uno concreto) y delegar en
|
||||||
// downloadFileFromServers
|
// downloadFileFromServers
|
||||||
boolean success = false;
|
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;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Método para descargar un fichero del peer servidor de ficheros
|
* Método para descargar un fichero del peer servidor de ficheros
|
||||||
*
|
*
|
||||||
@@ -181,9 +207,14 @@ public class NFControllerLogicP2P {
|
|||||||
// pedido, obtener nombre remoto, reservar nombre local sin colisiones, alternar
|
// pedido, obtener nombre remoto, reservar nombre local sin colisiones, alternar
|
||||||
// descarga de chunks y verificar hash final. Cerrar los sockets al terminar.
|
// 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;
|
return downloaded;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,10 +238,9 @@ public class NFControllerLogicP2P {
|
|||||||
/*
|
/*
|
||||||
* TODO: Devolver el puerto de escucha de nuestro servidor de ficheros
|
* TODO: Devolver el puerto de escucha de nuestro servidor de ficheros
|
||||||
*/
|
*/
|
||||||
|
if (fileServer != null) {
|
||||||
|
return fileServer.getServerSocket().getLocalPort();
|
||||||
|
} else return 0;
|
||||||
return NFServer.PORT;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -99,10 +99,26 @@ public class NFConnector {
|
|||||||
} else { return null; }
|
} else { return null; }
|
||||||
return filelist.toArray(new FileInfo[0]);
|
return filelist.toArray(new FileInfo[0]);
|
||||||
} catch (IOException e) { e.printStackTrace(); return null; }
|
} 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() {
|
public InetSocketAddress getServerAddr() {
|
||||||
return serverAddr;
|
return serverAddr;
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ public class PeerMessage {
|
|||||||
private String filenameVal;
|
private String filenameVal;
|
||||||
|
|
||||||
private byte[] fileData;
|
private byte[] fileData;
|
||||||
|
private int chunkNum;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -99,6 +100,14 @@ public class PeerMessage {
|
|||||||
this.fileData = 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
|
* Método de clase para parsear los campos de un mensaje y construir el objeto
|
||||||
* DirMessage que contiene los datos del mensaje recibido
|
* DirMessage que contiene los datos del mensaje recibido
|
||||||
@@ -149,11 +158,14 @@ public class PeerMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case PeerMessageOps.OPCODE_REQUEST_PEER_DL: {
|
case PeerMessageOps.OPCODE_REQUEST_PEER_DL: {
|
||||||
|
// buscar archivo supongo
|
||||||
|
}
|
||||||
|
case PeerMessageOps.OPCODE_PEER_DL: {
|
||||||
int longitudSubHash = (int) dis.readByte();
|
int longitudSubHash = (int) dis.readByte();
|
||||||
byte[] subHash = new byte[longitudSubHash];
|
byte[] subHash = new byte[longitudSubHash];
|
||||||
dis.readFully(subHash);
|
dis.readFully(subHash);
|
||||||
break;
|
|
||||||
// buscar archivo supongo
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ public class NFServer implements Runnable {
|
|||||||
|
|
||||||
msgOut.setFileHash(archivo.fileHash);
|
msgOut.setFileHash(archivo.fileHash);
|
||||||
msgOut.setFileSize(archivo.fileSize);
|
msgOut.setFileSize(archivo.fileSize);
|
||||||
msgOut.setFilenameVal(archivo.fileName);
|
msgOut.setFilenameVal(archivo.filePath + archivo.fileName);
|
||||||
msgOut.setFilenameLong((byte)archivo.fileName.length());
|
msgOut.setFilenameLong((byte)archivo.fileName.length());
|
||||||
msgOut.setLast(false);
|
msgOut.setLast(false);
|
||||||
if (i == archivos.length - 1) msgOut.setLast(true);
|
if (i == archivos.length - 1) msgOut.setLast(true);
|
||||||
|
|||||||
@@ -259,6 +259,7 @@ public class DirectoryConnector {
|
|||||||
byte[] resp = sendAndReceiveDatagrams(pingBytes);
|
byte[] resp = sendAndReceiveDatagrams(pingBytes);
|
||||||
String respStr = new String(resp, 0, resp.length);
|
String respStr = new String(resp, 0, resp.length);
|
||||||
DirMessage respPing = DirMessage.fromString(respStr);
|
DirMessage respPing = DirMessage.fromString(respStr);
|
||||||
|
System.out.println("pingDir - " + respPing.getOperation());
|
||||||
success = (respPing.getOperation().equals(DirMessageOps.OPERATION_PING_OK));
|
success = (respPing.getOperation().equals(DirMessageOps.OPERATION_PING_OK));
|
||||||
|
|
||||||
|
|
||||||
@@ -356,8 +357,13 @@ public class DirectoryConnector {
|
|||||||
long filesize = -1;
|
long filesize = -1;
|
||||||
String filehash = null;
|
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);
|
return new DownloadedFile(filename, filesize, fileData, filehash);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,6 +90,10 @@ public class DirMessage {
|
|||||||
return operation;
|
return operation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setOperation(String op) {
|
||||||
|
this.operation = op;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* TODO: (Boletín MensajesASCII) Crear métodos getter y setter para obtener los
|
* TODO: (Boletín MensajesASCII) Crear métodos getter y setter para obtener los
|
||||||
* valores de los atributos de un mensaje. Se aconseja incluir código que
|
* valores de los atributos de un mensaje. Se aconseja incluir código que
|
||||||
@@ -213,7 +217,7 @@ public class DirMessage {
|
|||||||
|
|
||||||
for (int i = 0; i < archivos.length; i++) {
|
for (int i = 0; i < archivos.length; i++) {
|
||||||
String[] atributos = archivos[i].split(":");
|
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;
|
listaArchivos[i] = archivo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,7 +284,7 @@ public class DirMessage {
|
|||||||
sb.append(FIELDNAME_FILELIST + DELIMITER);
|
sb.append(FIELDNAME_FILELIST + DELIMITER);
|
||||||
for (int i = 0; i < fileList.length; i++) {
|
for (int i = 0; i < fileList.length; i++) {
|
||||||
FileInfo f = fileList[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) {
|
if (i < fileList.length - 1) {
|
||||||
sb.append(','); // para evitar una coma al final
|
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
|
* done: (Boletín MensajesASCII) Comprobamos si el protocolId del mensaje del
|
||||||
* cliente coincide con el nuestro.
|
* cliente coincide con el nuestro.
|
||||||
*/
|
*/
|
||||||
msgToSend = new DirMessage(operation);
|
|
||||||
String protocolId = receivedMsg.getProtocolId();
|
String protocolId = receivedMsg.getProtocolId();
|
||||||
System.out.println(protocolId.equals(NanoFiles.PROTOCOL_ID));
|
System.out.println(protocolId.equals(NanoFiles.PROTOCOL_ID));
|
||||||
if (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 {
|
} else {
|
||||||
operation = DirMessageOps.OPERATION_PING_BAD;
|
msgToSend.setOperation(DirMessageOps.OPERATION_PING_BAD);
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
* done: (Boletín MensajesASCII) Construimos un mensaje de respuesta que indique
|
* 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.
|
* añade sufijos .1, .2, etc. hasta encontrar un nombre libre.
|
||||||
*/
|
*/
|
||||||
public static Path chooseAvailableName(String baseName) {
|
public static Path chooseAvailableName(String baseName) {
|
||||||
|
System.out.println(baseName);
|
||||||
Path path = Paths.get(baseName);
|
Path path = Paths.get(baseName);
|
||||||
int suffix = 1;
|
int suffix = 1;
|
||||||
while (Files.exists(path)) {
|
while (Files.exists(path)) {
|
||||||
|
|||||||
Reference in New Issue
Block a user