Ver Mensaje Individual
  #42 (permalink)  
Antiguo 31/08/2006, 16:30
antony_fire
 
Fecha de Ingreso: junio-2005
Ubicación: Cucuta
Mensajes: 62
Antigüedad: 18 años, 10 meses
Puntos: 2
Tranferir archivos con sockets en java

Tema: Transferencia de archivos usando sockets
Pregunta: ¿Como puedo enviar archivos de cualquier tipo usando sockets?
Respuesta: La solución a este problema es muy sencilla, se establece una comnicación cliente - servidor y se transfiren los bytes pertencientes al archivo a transmitir, en el ejemplo que se muestra a continuación el cliente envía un archivo de nombre php.pdf al servidor y este lo escribe en su disco.

Servidor.java
Código:
/*
 * Servidor.java
 *
 * Author: Antony Delgado
 * Created: 31 de Agosto de 2006 
 */

import java.net.ServerSocket;
import java.net.Socket;
public class Servidor implements Runnable {
    ServerSocket server;
    public Servidor() {
        try {
            //CREAMOS EL SOCKET DEL SERVIDOR
            server=new ServerSocket(2002);
            System.out.println("Servidor corriendo...");
        } catch(Exception e) {
            System.out.println("Error al correr el servidor\n"+e);
            System.exit(1);
        }
    }
    
    public void run() {
        Socket client=null;
        while (true) {
            if (server==null)
                return;
            try {
                //ESPERA A QUE LLEGUE UN CLIENTE
                client=server.accept();
                System.out.println("Llegó un cliente!");
            } catch(java.io.IOException e) {
                System.err.println("No se pudo establecer conexión " + e.getMessage());
            }
            try {
                //ABRIMOS UN BUFER PARA DESCARGAR LO QUE EL CLIENTE NOS ESTÁ ENVIANDO
                java.io.InputStream in = client.getInputStream();
                //CREAMOS LA INSTANCIA PARA ESCRIBIR EL ARCHIVO EN DISCO
                java.io.FileOutputStream out = new java.io.FileOutputStream(new java.io.File("C:\\php.pdf"));
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            } catch(java.io.IOException e) {
                System.out.println("Error: " + e);
            }
        }
    }
    
    public static void main(String a[]) {
        Servidor servidor = new Servidor();
        // Ponemos a correr nuestro hilo servidor
        new Thread(servidor).start();
    }
}
Cliente.java
Código:
/*
 * Cliente.java
 *
 * Author: Antony Delgado
 * Created: 31 de Agosto de 2006 
 */

import java.net.Socket;
import java.io.InputStreamReader;

public class Cliente {
    private String ip = "127.0.0.1";//O localhost o la que quieras 192.168.0.1 etc...
    private int puerto = 2002;
    private String nomArchivo = "D:\\Antony\\REDES\\php.pdf";
    public Cliente(){
        Socket socket = null;
        java.io.FileInputStream in = null;
        java.io.FileOutputStream pt = null;
        try {
            socket = new Socket(ip,puerto);
            pt = (java.io.FileOutputStream)socket.getOutputStream();//
            in = new java.io.FileInputStream(new java.io.File(nomArchivo));
        } catch(Exception e) {
            System.out.println("No se pudo crear la conexión\n"+e);
        }
        try {
            socket.sendUrgentData(100);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0 ){
                pt.write(buf, 0, len);
            }
            pt.close();
            in.close();
            socket.close();
        } catch(Exception e) {
            System.out.println("Error al enviar mensaje\n"+e);
        }
    } 
    public static void main(String a[]) {
        new Cliente();
    }
}
Java, Que nota de lenguaje

Última edición por antony_fire; 31/08/2006 a las 16:33 Razón: Se ven muy gay los corazoncitos que tenía