Transferencia de fichero por socket en Java

| 2013-09-19 | 3 Comentarios »

En este ejemplo vamos a abrir un servidor y un cliente. El cliente enviará un fichero y el nombre del fichero al servidor. El servidor guardará el fichero recibido en el directorio donde se esté ejecutando. La idea es, por tanto, ver cómo enviamos un fichero por un socket, sin liar la forma de pedir el fichero, ni hacer hilos para atender muchos clientes y muchas peticiones ni nada de eso. Solo leer el fichero y enviarlo por el socket.

El protocolo de transporte usado es TCP, para así garantizar que la transferencia se realice satisfactoriamente.

Servidor:


import java.net.*;
import java.io.*;

class servidor{
 public static void main (String[] args){

ServerSocket server;
 Socket connection;

DataOutputStream output;
 BufferedInputStream bis;
 BufferedOutputStream bos;

byte[] receivedData;
 int in;
 String file;

try{
 //Servidor Socket en el puerto 5000
 server = new ServerSocket( 5000 );
 while ( true ) {
 //Aceptar conexiones
 connection = server.accept();
 //Buffer de 1024 bytes
 receivedData = new byte[1024];
 bis = new BufferedInputStream(connection.getInputStream());
 DataInputStream dis=new DataInputStream(connection.getInputStream());
 //Recibimos el nombre del fichero
 file = dis.readUTF();
 file = file.substring(file.indexOf('\\')+1,file.length());
 //Para guardar fichero recibido
 bos = new BufferedOutputStream(new FileOutputStream(file));
 while ((in = bis.read(receivedData)) != -1){
 bos.write(receivedData,0,in);
 }
 bos.close();
 dis.close();
 }
 }catch (Exception e ) {
 System.err.println(e);
 }
 }
}

Cliente:


import java.net.*;
import java.io.*;

class cliente{
public static void main (String[] args){
 DataInputStream input;
 BufferedInputStream bis;
 BufferedOutputStream bos;
 int in;
 byte[] byteArray;
 //Fichero a transferir
 final String filename = "c:\\test.pdf";

try{
 final File localFile = new File( filename );
 Socket client = new Socket("localhost", 5000);
 bis = new BufferedInputStream(new FileInputStream(localFile));
 bos = new BufferedOutputStream(client.getOutputStream());
 //Enviamos el nombre del fichero
 DataOutputStream dos=new DataOutputStream(client.getOutputStream());
 dos.writeUTF(localFile.getName());
 //Enviamos el fichero
 byteArray = new byte[8192];
 while ((in = bis.read(byteArray)) != -1){
 bos.write(byteArray,0,in);
 }

bis.close();
 bos.close();

}catch ( Exception e ) {
 System.err.println(e);
 }
 }
}

Espero que les sirva el ejemplo, se esperan comentarios!!

Acerca del autor: Rodrigo Paszniuk

Ingeniero Informático, amante de la tecnología, la música, el ciclismo y aprender cosas nuevas.




SEGUÍNOS EN FACEBOOK


GITHUB