Laboratorio 1 - Sockets

1️⃣
Parte 1/3
La primera parte de la práctica nos pedirá que nos conectemos a un servidor FTP para descargarnos el enunciado de la siguiente parte de la práctica
 

Conexión al servidor FTP

Para conectarnos al servidor FTP usaremos el comando:
  • sftp <usuario>@<direccion_ip>
Hay que tener en cuenta que el usuario y la dirección IP nos la tendrán que decir en el enunciado.
Ejemplo
sftp 
🔒
A continuación nos saldrá un mensaje en la consola para que introduzcamos la contraseña. ⚠️ Probablemente cuando pulseis una tecla no aparezcan los caracteres en la pantalla, pero es normal, si que se están introduciendo pero no los vemos por seguridad. Simplemente introduce la contraseña y pulsa ENTER

Descargar archivos del servidor FTP

Puedes iniciar sesión en el servidor FTP, podremos ejecutar los siguientes comandos
  • dir → Lista todos los archivos del servidor
  • get <archivo> → Descarga un archivo concreto del servidor
    • 💡 Si ejecutamos get * descargaremos todos los archivos disponibles. Este comando es util para no tener que escribir el nombre completo de todos los archivos
2️⃣
Parte 2/3
Esta parte nos pide que establezcamos una conexión TCP con un servidor al cual le proporcionaremos unos datos y este nos devolverá un archivo
💡
Los datos que hay que enviar los dice el enunciado
💡
El siguiente código muestra como conectarse al servidor, enviar unos datos, y recibir un archivo el cual guardará en la misma ruta en la cual estamos ejecutando el código
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.Socket;

class clientTCP {

  public static void sendThenWriteToFile(String argv[]) throws Exception {
    // Socket configuration
    Socket socket = new Socket("212.128.3.86", 6789); // <--- Change this to the server IP and port
    // Outgoing data stream
    DataOutputStream streamToServer = new DataOutputStream(
      socket.getOutputStream()
    );

    // Prepare the data to send
    String sentence = "Example data to send to the server";
    // Send the data
    streamToServer.writeBytes(sentence);

    // Prepare the file to write the response
    FileOutputStream file = new FileOutputStream("output.pdf"); // <--- Change this to the desired file name

    // Read the response
    int b = socket.getInputStream().read(); // Read the first byte
    while (b != -1) { // Read until the end of the file. `-1` means the end of the stream
      file.write(b); // Write the byte to the file
      b = socket.getInputStream().read(); // Read the next byte
    }

    // Close the connection and the file
    socket.close();
    file.close();
  }
}
3️⃣
Parte 3/3
Esta parte es parecida a la anterior, pero ahora usando el protocolo UDP para enviar los datos
💡
Los datos que hay que enviar los dice el enunciado
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class clientUDP {
  public static void sendThenWriteToFile(String args[]) throws Exception {
    // Prepare IP address
    InetAddress dirIP = InetAddress.getByName("212.128.3.86");
    // Create an UDP socket
    DatagramSocket socket = new DatagramSocket();

    // ------------------------------------------------[ Send data ]------------------------------------------------
    // Prepare the data to send
    String sentence = "This is some example data...";
    byte[] outBuff = sentence.getBytes(); // Convert the string to a byte array

    // Prepare the datagram (create datagram packet: data, length, IP, port)
    DatagramPacket outPac = new DatagramPacket(outBuff, outBuff.length, dirIP, 9500);

    // Send the datagram over the socket
    socket.send(outPac);

    // ------------------------------------------------[ Recieve data ]------------------------------------------------

    //Recibimos un datagrama
    byte[] inputBuff = new byte[1024];
    DatagramPacket inPac = new DatagramPacket(inputBuff, inputBuff.length);
    socket.receive(inPac);
    socket.close();

    String newSentence = new String(inPac.getData());
    System.out.println("DEL SERVIDOR:" + newSentence);

  }
}