Transferencia de arquivos via Sockets

4 respostas
M

Pessoal eu estou com um projeto que simula o MSN e so falta o envio de arquivos, nunca fiz isso e nao encontro bons tutoriais, alguem pode me da uma luz?

Desde já, Obrigado

4 Respostas

T

poste seu codigo para termos ideia de como vc esta fazendo …ai fica mais facil …flw

M
Esse é o de mandar o arquivo
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MandaArquivo extends Servidor implements Runnable {


	public MandaArquivo(Socket cliente){
		setCliente(cliente);
	}
	static Socket cliente;
	static MandaArquivo ma;
	static RecebeArquivo ra;
	static void setCliente(Socket socket){
		cliente = socket;
	}
	
	
	int porta = 1234;
	static String caminho;
		public void run(){
		
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Digite o arquivo, ou o caminho relativo: ");
        caminho = scan.nextLine();
        
     
        
        try{
            System.out.println("[Conectando Servidor...]");
            Socket cliente = new Socket(ip, porta);
            
            System.out.println("[Conexao aceita de: "+cliente.getInetAddress().toString()+"]");
            
            System.out.println("[Enviando arquivo '"+caminho+"'");
            
            // abertura do arquivo
            BufferedInputStream arquivo = new BufferedInputStream(new FileInputStream(caminho));
            
            // abertura de canal modo texto
            PrintWriter saidaTexto = new PrintWriter(cliente.getOutputStream(), true);
            
            // obtenção e envio dos dados do arquivo
            File file = new File(caminho);
            saidaTexto.println(file.getName());
            
            long sent = 0;
            long total = file.length();
            
            saidaTexto.println(total+"");
            
            // fecha canal modo texto
            saidaTexto.close();
            
            // fecha conexao
            cliente.close();
            
            // reabre conexao
            cliente = new Socket(ip, porta);
            
            // abertura canal binario
            BufferedOutputStream saidaBin = new BufferedOutputStream(cliente.getOutputStream());
            
            while(sent+256 < total){
                
                // cria array para bloco
                byte[] dados = new byte[256];
                
                // le dados para bloco
                arquivo.read(dados, 0, 256);
                
                // envia bloco
                saidaBin.write(dados, 0, 256);
                
                // totaliza blocos
                sent += 256;
            }
            
            if(sent < total){
                int fim = (int) (total - sent);
                
                //cria array para bloco final
                byte dados[] = new byte[fim];
                
                // le dados para bloco final
                arquivo.read(dados, 0, fim);
                
                // envia bloco final
                saidaBin.write(dados, 0, fim);
            }
            
            saidaBin.flush();
            // fecha canal binario
            saidaBin.close();
            
            // fecha arquivo
            arquivo.close();
            
            System.out.println("["+total+" bytes enviados]");
            
            // fecha conexao
            cliente.close();
            
            System.out.println("[Conexao encerrada]");
            
            
        }catch(Exception e){
            System.out.println("Erro!\n");
            e.printStackTrace();
        }
        
    }
		 
}
E esse é o de receber:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class RecebeArquivo extends Servidor implements Runnable{

	public RecebeArquivo(Socket cliente){
		setCliente(cliente);
	}
	static Socket cliente;
	static MandaArquivo ma;
	static RecebeArquivo ra;
	static void setCliente(Socket socket){
		cliente = socket;
	}
    public void run(){
        try{
            
            System.out.println("[Criando Servidor...]");
            
            
            
            System.out.println("[Servidor operando na porta 1234]");
            
            while(true){
                System.out.println("[Esperando conexao...]");
                
                Socket cliente = servidor.accept();
                
                System.out.println("[Conexao aberta de: "+
                        cliente.getInetAddress().toString()+"]");
                
                // abre canal modo texto
                BufferedReader entradaTexto = new BufferedReader(
                        new InputStreamReader(cliente.getInputStream()));
                
                // recebe dados do arquivo a ser transferido
                String nomeArq = entradaTexto.readLine();
                System.out.println("[Recebendo arquivo: '"+MandaArquivo.caminho+"']");
                long recv = 0;
                long total = Long.parseLong(entradaTexto.readLine());
                
                // fecha canal modo texto
                entradaTexto.close();
                
                // reabre conexao
                cliente = servidor.accept();
                
                // abre canal binario
                BufferedInputStream entradaBin = new BufferedInputStream(cliente.getInputStream());
            
                // abre arquivo para dados transferidos
                BufferedOutputStream arquivo = new BufferedOutputStream(new FileOutputStream(nomeArq));
                
                while(recv+256 < total){
                    
                    // cria array para bloco
                    byte dados[] = new byte[256];
                    
                    // le bloco
                    entradaBin.read(dados, 0, 256);
                    
                    // grava bloco
                    arquivo.write(dados, 0, 256);
                    
                    // totaliza blocos
                    recv += 256;
                }
                
                if(recv < total){
                    int fim = (int) (total - recv);
                    
                    // cria array para bloco final
                    byte dados[] = new byte[fim];
                    
                    // le bloco final
                    entradaBin.read(dados, 0, fim);
                    
                    // grava bloco final
                    arquivo.write(dados, 0, fim);                    
                }
                
                // fecha canal binario
                entradaBin.close();
                
                // fecha arquivo
                arquivo.close();
                System.out.println("["+total+" bytes recebidos]");
                
                // fecha conexao
                cliente.close();
                System.out.println("[Conexao encerrada]");
            }
            
        }catch(Exception e){
            System.out.println("Erro!\n");
            e.printStackTrace();
        }
    }
}

Lembrando q essa é uma rede p2p, portanto nao posso fazer servidor e cliente independentes

M

? groupId, artifactId, version:
These elements are self-explanatory, and you will see them often. This trinity represents the
coordinate of a specific project in time, demarcating it as a dependency of this project. You may
be thinking: “This means that my project can only depend upon Maven artifacts!” The answer
is, “Of course, but that’s a good thing.” This forces you to depend solely on dependencies that
Maven can manage. There are times, unfortunately, when a project cannot be downloaded from
the central Maven repository. For example, a project may depend upon a jar that has a closed-
source license which prevents it from being in a central repository. There are three methods for
dealing with this scenario.
1 Install the dependency locally using the install plugin. The method is the simplest
recommended method. For example:
mvn install:install-file -Dfile=non-maven-proj.jar -
DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1
Notice that an address is still required, only this time you use the command line and the
install plugin will create a POM for you with the given address.
2 Create your own repository and deploy it there. This is a favorite method for companies
with an intranet and need to be able to keep everyone in synch. There is a Maven goal called
deploy:deploy-file which is similar to the install:install-file goal (read the
plugin’s goal page for more information).
3 Set the dependency scope to system and define a systemPath. This is not recommended,
however, but leads us to explaining the following elements:
? classifier:
The classifier allows to distinguish artifacts that were built from the same POM but differ in their
content. It is some optional and arbitrary string that - if present - is appended to the artifact name
just after the version number.
As a motivation for this element, consider for example a project that offers an artifact targeting
JRE 1.5 but at the same time also an artifact that still supports JRE 1.4. The first artifact could be
equipped with the classifier jdk15 and the second one with jdk14 such that clients can choose
which one to use.
Another common use case for classifiers is the need to attach secondary artifacts to the project’s
main artifact. If you browse the Maven central repository, you will notice that the classifiers
©2009, The Apache Software Foundation ? ALL RIGHTS RESERVED.
15 POM Reference 62
sources and javadoc are used to deploy the project source code and API docs along with the
packaged class files.
? type:
Corresponds to the dependant artifact’s packaging type. This defaults to jar. While it usually
represents the extension on the filename of the dependency, that is not always the case. A
type can be mapped to a different extension and a classifier. The type often correspongs to the
packaging used, though this is also not always the case. Some examples are jar, ejb-client
and test-jar. New types can be defined by plugins that set extensions to true, so this is not
a complete list.
? scope:
This element refers to the classpath of the task at hand (compiling and runtime, testing, etc.) as
well as how to limit the transitivity of a depedency. There are five scopes available:
? compile - this is the default scope, used if none is specified. Compile dependencies are
available in all classpaths. Furthermore, those dependencies are propagated to dependent
projects.
? provided - this is much like compile, but indicates you expect the JDK or a container to
provide it at runtime. It is only available on the compilation and test classpath, and is not
transitive.
? runtime - this scope indicates that the dependency is not required for compilation, but is for
execution. It is in the runtime and test classpaths, but not the compile classpath.
? test - this scope indicates that the dependency is not required for normal use of the
application, and is only available for the test compilation and execution phases.
? system - this scope is similar to provided except that you have to provide the JAR which
contains it explicitly. The artifact is always available and is not looked up in a repository.
? systemPath:
is used only if the the dependency scope is system. Otherwise, the build will fail if this element
is set. The path must be absolute, so it is recommended to use a property to specify the machine-
specific path (more on properties below), such as ${java.home}/lib. Since it is assumed
that system scope dependencies are installed a priori, Maven will not check the repositories for
the project, but instead checks to ensure that the file exists. If not, Maven will fail the build and
suggest that you download and install it manually.
? optional:
Marks optional a dependency when this project itself is a dependency. Confused? For example,
imagine a project A that depends upon project B to compile a portion of code that may not
be used at runtime, then we may have no need for project B for all project. So if project X
adds project A as its own dependency, then Maven will not need to install project B at all.
Symbolically, if => represents a required dependency, and --> represents optional, although
A=>B may be the case when building A X=>A–>B would be the case when building X.
In the shortest terms, optional lets other projects know that, when you use this project, you do
not require this dependency in order to work correctly.
15. Exclusions
Exclusions explicitly tell Maven that you don’t want to include the specified project that is a
dependency of this dependency (in other words, its transitive dependency). For example, the maven-
embedder requires maven-core, and we do not wish to use it or its dependencies, then we would
add it as an exclusion.

E

Dá uma olhada neste site http://www.java-tips.org/java-se-tips/javax.swing/how-to-create-a-download-manager-in-java.html.
tem um exemplo completo de como criar um gerenciador de downloads usando Java.

E neste tem um exemplo de envio de arquivos usando sockets: http://www.rgagnon.com/javadetails/java-0542.html

Até

Criado 18 de junho de 2009
Ultima resposta 2 de out. de 2009
Respostas 4
Participantes 3