Posts tagged ‘enviar archivos por socket java’

julio 18, 2010

Enviar Archivos por [Sockets] socket a server

Ejemplo sencillo de como enviar archivos via sockets en Java

Consola
======================================================
Starting server…
>Server started on port: 8081
>Waiting for connections…
>>New Connection Received: /127.0.0.1
>>Starting thread for connection…
>>Receiving file: bt4-r2.iso.part
>>Please wait…
>>Task completed!

======================================================

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * @author Leyer
 */
class _Server extends ServerSocket implements Runnable{
	private boolean running = false;
	
	public _Server(int port, int backlog, InetAddress bindAddr)
			throws IOException {
		super(port, backlog, bindAddr);
		running=true;
		System.out.println(">Server started on port: "+port);
	}
	public void init(){
		new Thread(this).start();
	}
	private class Connection extends Thread{
		
		public static final int DEFAULT_BUFFER_SIZE = 1024;
		
		private DataInputStream dataInputStream;
		private Socket socket;
		
		public Connection(Socket socket){
			try {
				this.socket=socket;
				dataInputStream=new DataInputStream(socket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		@Override
		public void run(){
			try{
				String fileName = dataInputStream.readUTF();
				System.out.println(">>Receiving file: "+fileName);
				System.out.println(">>Please wait...");
				FileOutputStream fileOutputStream=new FileOutputStream(fileName);
				byte b[]=new byte[DEFAULT_BUFFER_SIZE];
				int len=0,off=0;
				while((dataInputStream.read(b))>0)fileOutputStream.write(b, off, len);
				fileOutputStream.flush();
				fileOutputStream.close();
				System.out.println(">>Task completed!");
				} catch (IOException e) {
					e.printStackTrace();
			}finally{
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public boolean isRunning(){
		return running;
	}
	@Override
	public void run() {
		System.out.println(">Waiting for connections...");
		Socket socket=null;
		while(running){
			try {
				socket=accept();
				System.out.println(">>New Connection Received: "+socket.getInetAddress());
				System.out.println(">>Starting thread for connection...");
				Connection connection=new Connection(socket);
				connection.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
class _Socket extends Socket implements Runnable{
	public static final int DEFAULT_BUFFER_SIZE = 1024;
	
	private DataOutputStream dataOutputStream;

	private FileInputStream fileInputStream;
	public _Socket(InetAddress address,int port) throws IOException{
		super(address,port);
		initStreams(getInputStream(), getOutputStream());
	}
	public void initStreams(InputStream inputStream,OutputStream outputStream){
		dataOutputStream=new DataOutputStream(outputStream);
	}
	public void upFile(File file){
		if(file.exists()&&file.length()>0){
			try {
				fileInputStream=new FileInputStream(file);
				dataOutputStream.writeUTF(file.getName());
		        dataOutputStream.flush();
		        new Thread(this).start();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void run() {
		byte b[]=new byte[DEFAULT_BUFFER_SIZE];
		int len=0,off=0;
		try {
			while((len=fileInputStream.read(b))>0)
				dataOutputStream.write(b, off, len);
			dataOutputStream.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
			try {
				close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
public class Transfers{
  public static void main(String[] argv) {
	  try {
	    System.out.println("Starting server...");
		_Server _Server=new _Server(8081, 500, InetAddress.getByName("127.0.0.1"));
		_Server.init();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(_Server.isRunning())
		new _Socket(InetAddress.getByName("127.0.0.1"), 8081).upFile(new File("C:\\bt4-r2.iso.part"));
	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
		}