Boa Noite Pessoal,
Primeiramente agradecer a Felipe.JavaMan por ter mando seu código e a todos que tentaram me ajudar. Olhem pessoa finalmente eu consegui um resoltado no meu projeto a vou posta-lo aqui pra que seja de conhecimento a todos.
É o seguinte, tenho um servidor que faz a criptografia e descriptografia de um arquivo. E o cliente faz o envio ao servidor desse arquivo informando-o se deve ser cripto ou descripto e o servidor o faz e o envia de volta ao cliente assim como desejado. Obs: Na criptografia eu nao consegui implementar no meu projeto que esta muito em cima de ser entregue na faculdade por conta do tempo e fiz o seguinte quando vou enviar o arquivo do servidor ao cliente eu na hora que estou escrevendo adiciono ao numero de byte desse arquivo "1" e na descriptografia eu retiro subtraindo esse mesmo valor "1" ( " out.write(aux+1); " e " out.write(aux-1); " ). E esse projetinho tambem enviar um diretorio ou um aquivo unico, pois, antes de envia-lo ao servidor o cliente primeiramente compacta pra resumir o tamanho e tornar o envio mais rapido. E so ressaltando esse codigo de compactação que usei depois que enviei ao meu professor foi que observei que estava com uma falha ou seja ele compacta de mais e alguns arquivos ele nao consegue devolve-los intactos. Pronto! É isso ai pessoal, sei que nao foi a melhor forma mais sou muito novo em programação e principalmente em JAVA foi o que pude fazer so espero que possam ajudar alguém assim como precisei saber como enviava um arquivo ao servidor e recebia de volta. E é claro vou precisar sempre. Abraço a todos.
Abaixo esta Primeiramente o Cliente e Depois o Servidor...
Classes para o Cliente
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class ClienteJFrame extends javax.swing.JFrame {
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}
private JLabel TServido;
private JTextField IPTexto;
private JTextField ArquivoTexto;
private static JTextArea TextoInformativo;
private JButton botaoCriptografia;
private JButton Abrir;
private JButton botaoDescriptografia;
private JLabel Console;
private JScrollPane jScrollPane1;
private JLabel NArquivo;
private Frame frame;
private ClienteSocket cliente = new ClienteSocket();
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClienteJFrame inst = new ClienteJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public ClienteJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
this.setTitle("Socket Cliente");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
{
TServido = new JLabel();
getContentPane().add(TServido);
TServido.setBounds(12, 21, 53, 16);
TServido.setText("Servidor:");
}
{
IPTexto = new JTextField();
IPTexto.setText("127.0.0.1");
getContentPane().add(IPTexto);
IPTexto.setBounds(65, 19, 109, 21);
}
{
NArquivo = new JLabel();
getContentPane().add(NArquivo);
NArquivo.setText("Arquivo:");
NArquivo.setBounds(12, 55, 53, 14);
}
{
ArquivoTexto = new JTextField();
getContentPane().add(ArquivoTexto);
ArquivoTexto.setBounds(65, 52, 243, 21);
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(15, 103, 418, 173);
{
TextoInformativo = new JTextArea();
jScrollPane1.setViewportView(TextoInformativo);
TextoInformativo.setBounds(16, 103, 417, 171);
}
}
{
Console = new JLabel();
getContentPane().add(Console);
Console.setText("Console Informativo");
Console.setBounds(144, 83, 116, 14);
}
{
botaoDescriptografia = new JButton();
getContentPane().add(botaoDescriptografia);
botaoDescriptografia.setText("Descriptografia");
botaoDescriptografia.setBounds(239, 291, 162, 27);
botaoDescriptografia.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
botaoDescriptografiaActionPerformed(evt);
}
});
}
{
Abrir = new JButton();
getContentPane().add(Abrir);
Abrir.setText("Abrir");
Abrir.setBounds(330, 52, 76, 21);
Abrir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AbrirActionPerformed(evt);
}
});
}
{
botaoCriptografia = new JButton();
getContentPane().add(botaoCriptografia);
botaoCriptografia.setText("Criptografia");
botaoCriptografia.setBounds(27, 291, 162, 27);
botaoCriptografia.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
botaoCriptografiaActionPerformed(evt);
}
});
}
pack();
this.setSize(460, 360);
} catch (Exception e) {
e.printStackTrace();
}
}
private void botaoDescriptografiaActionPerformed(ActionEvent evt) {
String ip = IPTexto.getText();
String caminho = ArquivoTexto.getText();
//int porta = Integer.parseInt(PortaTexto.getText());
int tipo = 1;
cliente.criarSocket(ip,caminho,tipo);
//apagando conteudos
//IPTexto.setText("");
ArquivoTexto.setText("");
}
/*Funcao que me permite retornar mensagens no console
* da aplicação que é um TextoArea*/
public static void informarEvento(final String mensagem){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
TextoInformativo.append(mensagem);
}
});
}
private void AbrirActionPerformed(ActionEvent evt) {
TraduzirFChooser.traduzirFileChooser();
JFileChooser fc = new JFileChooser();
// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setCurrentDirectory(new File("C:\\"));
fc.setDialogTitle("Abrir");
int res = fc.showOpenDialog(null);
if(res == JFileChooser.APPROVE_OPTION){
File diretorio = fc.getSelectedFile();
String filename = diretorio.getAbsolutePath();
ArquivoTexto.setText(filename);
}
}
private void botaoCriptografiaActionPerformed(ActionEvent evt) {
String ip = IPTexto.getText();
String caminho = ArquivoTexto.getText();
//int porta = Integer.parseInt(PortaTexto.getText());
int tipo = 0;
cliente.criarSocket(ip,caminho, tipo);
//apagando conteudos
//IPTexto.setText("");
ArquivoTexto.setText("");
}
}
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class ClienteSocket {
private Compactar compac = new Compactar();
private Socket sockt;
private final int porta = (2343);
private String ip;
private DataOutputStream out;
private DataInputStream in;
private FileInputStream file = null;
private String filename = null;
private final String arquivoCripto = "C:\\Arquivos Criptografados\\";
byte[] bufferCli;
public void criarSocket(String Ip, String caminho, int tipo){
File s = new File(arquivoCripto);
if(!s.isDirectory()){
s.mkdir();
}
this.ip = Ip;
try {
sockt = new Socket(Ip,porta);
ClienteJFrame.informarEvento("O socket foi criado! \n");
if(tipo == 0){
String compactacao = (arquivoCripto + "compactacao.zip");
compac.zip(compactacao, caminho);
enviar(compactacao, tipo);
try{
new File(compactacao).delete();
}catch (Exception e) {
e.printStackTrace();
}
}else if(tipo == 1){
enviar(caminho, tipo);
}
}catch(IOException err){
ClienteJFrame.informarEvento("Erro na criação do Socket!\n");
}
}
public void socketReceber( int tipo ){
try {
//Socket sockt = new Socket("127.0.0.1",2343); //aqui eu dereciono o socket ao servidor
sockt = new Socket(ip,porta);
ClienteJFrame.informarEvento("O socket foi criado! \n");
solicita( tipo );
}catch(IOException err){
ClienteJFrame.informarEvento("Erro na criação do Socket!\n");
}
}
/**
* Este metodo solicita uma ação do servidor
* @param tipo int
*/
private void solicita(int tipo) {
try{
out = new DataOutputStream (sockt.getOutputStream());
out.writeInt(tipo);
RecerberArquivo();
}catch (Exception e) {
e.printStackTrace();
}
}
public void enviar(String cam, int tipo){
filename = cam;
try{
/*aquei eu prepraro o outputstream para o enviu do arquivo*/
out = new DataOutputStream (sockt.getOutputStream());
/*aqui eu abro e carrego o arquivo em file*/
file = new FileInputStream (filename);
/*aqui eu carrego o arquivo file em DataInputStream->in para envialo*/
in = new DataInputStream(file);
/*aqui eu criu um buffer de bytes com tamanho de 128 bytes para i enviu*/
byte buffer[] = new byte[2024];
out.writeInt(0);
/*aqui eu enviu os dados/arquivo*/
while(in.read(buffer) != -1){
out.write(buffer,0,buffer.length);
}//
ClienteJFrame.informarEvento("O Arquivo foi enviado ao Servidor!\n");
out.close();//aqui eu fecho out pra poder criptar.
in.close();// //
fecharConexao();
if(tipo == 0){
socketReceber(1);
}else if(tipo == 1){
socketReceber(2);
}
}catch (IOException e) {
e.printStackTrace();
ClienteJFrame.informarEvento("Erro no Envio!\n");
}
}
public void RecerberArquivo(){
criarPastas("C:\\Arquivos Criptografados\\");
try {
in = new DataInputStream(sockt.getInputStream());
int tipo = in.readInt();
if(tipo == 1){
String nome = "Criptografia.zip";
int readByte = in.read();
out = new DataOutputStream (new FileOutputStream(arquivoCripto+nome));
bufferCli = new byte[in.available()];
String rec = null;
while (readByte !=-1) {
out.write((byte)readByte);
readByte = in.read();
rec = rec + readByte;
}
JOptionPane.showMessageDialog(null, "Seu arquivo/diretório foi criptografado e encontra-se na pasta: " +
" \n C:\\Arquivos Criptografados, com o nome: Criptografia.zip ", "Criptografia", JOptionPane.INFORMATION_MESSAGE);
}else if(tipo == 2){
String nome = "DesCriptografia.zip";
int readByte = in.read();
out = new DataOutputStream (new FileOutputStream(arquivoCripto+nome));
bufferCli = new byte[in.available()];
String rec = null;
while (readByte !=-1) {
out.write((byte)readByte);
readByte = in.read();
rec = rec + readByte;
}
JOptionPane.showMessageDialog(null, "Seu arquivo/diretório foi descriptografado e encontra-se na pasta: " +
" \n C:\\Arquivos Criptografados, com o nome: DesCriptografia.zip ", "Criptografia", JOptionPane.INFORMATION_MESSAGE);
}
ClienteJFrame.informarEvento("Arquivo Recebido do Servidor! \n");
out.close();
fecharConexao();
} catch (IOException e) {
ClienteJFrame.informarEvento("Erro no Recebimento do Arquivo! \n");
}
}/*Fim do Receber*/
/**
* Aque eu verifico se o diretorio existe e o crio
* @param diretorio
*/
public void criarPastas(String diretorio) {
String[] pastas = diretorio.split("\\\\");//.getText().split("\\\\");
String raiz = pastas[0].toString() + "\\";
for (int i = 0; i<pastas.length; i++) {
if (i>0) {
File dir = new File(raiz + pastas[i].toString());
if (!dir.exists()) {
dir.mkdir();
}
raiz = raiz + pastas[i].toString() + "\\";
}
}
}
public void fecharConexao(){
try {
sockt.close();
ClienteJFrame.informarEvento("Fim da Transação!\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Compactar {
/**
* Lê um arquivo passado no parâmetro para a memória.
* @param file Arquivo a ser lido.
* @return Arquivo lido em bytes.
* @throws Exception
*/
private byte[] read(File file) throws Exception {
byte[] result = null;
if (file != null && !file.isDirectory()) {
final long length = file.length();
result = new byte[(int) length];
InputStream fi = new FileInputStream(file);
byte b;
long count = 0;
while ((b = (byte) fi.read()) != -1) {
result[(int) count++] = b;
}
fi.close();
}
return result;
}
/**
* Adiciona um diretório ou arquivo a um ZipOutputStream instanciado.
* @param C:\\teste.zip
* @param C:\\Documents and Settings\\diego\\workspace\\Testando\\teste.zip
* @throws Exception
*/
private void addToZip(ZipOutputStream out, File file, String path) throws Exception {
byte data[] = null;
ZipEntry entry = null;
if (file != null) {
String name = file.getAbsolutePath();
name = name.substring(path.length() + 1, name.length()).replace( "\\","/");
ClienteJFrame.informarEvento(">>>> Adicionando: " + name+"\n");
//System.out.println(">>>> Adding: " + name);
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
addToZip(out, f, path);
}
} else {
entry = new ZipEntry(name);
out.putNextEntry(entry);
data = read(file);
if (data != null && data.length > 0) {
out.write(data, 0, data.length);
}
out.closeEntry();
out.flush();
}
}
}
}
/**
* Comprime um diretório ou arquivo.
* @param zipName - Nome no arquivo zip que será gerado, exemplo: C:\\Documents and Settings\\diego\\workspace\\Testando\\myzip.zip
* @param dirName - Nome do arquivo ou diretório a ser comprimido.
*/
public void zip(String zipName, String dirName) {
ZipOutputStream out = null;
FileOutputStream dest = null;
CheckedOutputStream checksum = null;
try {
dest = new FileOutputStream(new File(zipName));
checksum = new CheckedOutputStream(dest, new Adler32());
out = new ZipOutputStream(new BufferedOutputStream(checksum));
File dir = new File(dirName);
String parent = dir.getParent();
int length = parent.length();
String substring = parent.substring(0, length);
addToZip(out, dir, substring);
ClienteJFrame.informarEvento(">>>> checksum: " + checksum.getChecksum().getValue() +"\n");
//System.out.println(">>>> checksum: " + checksum.getChecksum().getValue());
} catch (Exception e) {
e.printStackTrace();
} catch (Error err) {
err.printStackTrace();
} finally {
try {
out.flush();
out.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Error err) {
err.printStackTrace();
}
}
}
// public static void main(String[] args)
// {
// new Compactar().zip("C:\\compactados.zip", "C:\\tt");
// }
}
Classes para o Servidor
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Servidor objeto = new Servidor();
ServidorJFrame tela = new ServidorJFrame();
tela.telaRun();
objeto.run();
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class ServidorJFrame extends javax.swing.JFrame {
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}
private JLabel NomeConsole;
private JScrollPane jScrollPane1;
private static JTextArea TextoConsole;
/**
* Auto-generated main method to display this JFrame
*/
public static void telaRun() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ServidorJFrame inst = new ServidorJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public ServidorJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("Tela Servidor");
getContentPane().setLayout(null);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
{
NomeConsole = new JLabel();
getContentPane().add(NomeConsole);
NomeConsole.setText("Console Informativo");
NomeConsole.setBounds(231, 12, 144, 16);
NomeConsole.setFont(new java.awt.Font("Tahoma",0,16));
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(46, 56, 499, 349);
{
TextoConsole = new JTextArea();
jScrollPane1.setViewportView(TextoConsole);
}
}
pack();
this.setSize(600, 500);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void informarEvento(final String mensagem){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
TextoConsole.append(mensagem);
}
});
}
private void botaoFimActionPerformed(ActionEvent evt) {
Servidor objeto = new Servidor();
try {
objeto.serv.close();
objeto.interrupt();
ServidorJFrame.informarEvento("Servidor foi finalizado! \n");
} catch (IOException e) {
//e.printStackTrace();
ServidorJFrame.informarEvento("Não foi possivel finalizar o Servidor! \n");
} catch (Throwable e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
/*Estou instanciando Serdivor e Criando um Thread!*/
public class Servidor extends Thread{
/*Aqui declaro uma variada como tipo socket servidor e inicio como nulo*/
ServerSocket serv = null;
/*Aqui declaro uma variada como tipo socket cliente e inicio como nulo*/
//Socket client = null;
/*Aqui eu defino a porta que meu servidor vai estar esperando o serviço*/
private final int port = (2343);
/*Aquei eu informo o caminho onde o servidor vai buscar o arquivo a ser enviado*/
private final String filename = "C:\\ServidorCripto\\";
private File ar_crip = new File("C:\\ServidorCripto\\arquivo.zip");
/*Aquei eu criu os dados para as entradas/escrita ->in, saida -> out
* e a excrita do arquivo ->file*/
private DataOutputStream out;
private DataInputStream in;
private FileInputStream file = null;
private String nomeAr = "arquivo.zip";
byte[] bufferCli;
String identIP;
private void CriarServidor(){
/*Aqui eu tentarei criar */
try{
serv = new ServerSocket(port);
ServidorJFrame.informarEvento("Servidor liberado e aguardando conexao na porta:\n");
criarPastas("C:\\ServidorCripto\\");
}catch(IOException e){
ServidorJFrame.informarEvento("Erro na liberação da porta especificada!\n");
}
while (true) {
/*aQuei declaro um entrada de true para o while,
* onde ele ficara de forma infinita
* e recebera varias conexões de clientes*/
try{
/*Aquei eu aceito a conexao com o cliente*/
Socket client = serv.accept();
ServidorJFrame.informarEvento("Cliente aceito em uma conxao!\n");
/*aque eu criu uma string que vai receber o metodo q
* me retorna uma outra string contendo o endereço ip*/
identIP = client.getInetAddress().getHostAddress();
ServidorJFrame.informarEvento("O Cliente Identificado: " + identIP+"\n");
aguardaAcao( client );
}catch(IOException e){
ServidorJFrame.informarEvento("Erro ao tentar enviar o arquivo!\n");
}
}/*fim do while*/
}/*CriarServidor()*/
private void aguardaAcao( Socket client) {
try {
in = new DataInputStream(client.getInputStream());
int tipo = in.readInt();
if(tipo == 0){
RecerberArquivo(client);
}else if(tipo == 1){
enviarCripto(tipo, client);
}else if(tipo == 2){
enviarDesCripto(tipo, client);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void criarPastas(String diretorio) {
String[] pastas = diretorio.split("\\\\");//.getText().split("\\\\");
String raiz = pastas[0].toString() + "\\";
for (int i = 0; i<pastas.length; i++) {
if (i>0) {
File dir = new File(raiz + pastas[i].toString());
if (!dir.exists()) {
dir.mkdir();
}
raiz = raiz + pastas[i].toString() + "\\";
}
}
}
public void RecerberArquivo(Socket client){
try {
out = new DataOutputStream (new FileOutputStream(filename+nomeAr));
in = new DataInputStream(client.getInputStream());
//int tipo = in.readInt();
bufferCli = new byte[in.available()];
int readByte = in.read();
String rec = null;
while (readByte !=-1) {
out.write((byte)readByte);
readByte = in.read();
rec = rec + readByte;
}
ServidorJFrame.informarEvento("Arquivo Recebido do Cliente:" + identIP+"\n");
out.close();
fecharConexao(client);
} catch (IOException e) {
ServidorJFrame.informarEvento("Erro no Recebimento do Arquivo do:" + identIP+"\n");
}//Fim do receber
}/*Fim do Receber*/
public void run(){
CriarServidor();
}/*fim do Run*/
public void enviarCripto(int tipo, Socket client){
//byte buffer[];
try{
out = new DataOutputStream (client.getOutputStream());
file = new FileInputStream (ar_crip);
BufferedInputStream in = new BufferedInputStream(file);
//byte buffer[] = new byte[2048];
out.writeInt(tipo);
int aux = 0;
while((aux =in.read()) != -1){//
out.write(aux+1);//(in.read());///buffer+1,0,buffer.length);
}//
ServidorJFrame.informarEvento("O Arquivo foi enviado ao Cliente!\n");
out.close();//aqui eu fecho out pra poder criptar.
in.close();// //
ar_crip.delete();
fecharConexao( client );
}catch (IOException e) {
ServidorJFrame.informarEvento("Erro no Envio!\n");
}
}
public void enviarDesCripto(int tipo, Socket client){
try{
out = new DataOutputStream (client.getOutputStream());
file = new FileInputStream (ar_crip);
BufferedInputStream in = new BufferedInputStream(file);
//byte buffer[] = new byte[2048];
out.writeInt(tipo);
int aux = 0;
while((aux = in.read()) != -1){//
out.write(aux-1);//(in.read());///buffer+1,0,buffer.length);
}//
ServidorJFrame.informarEvento("O Arquivo foi enviado ao Cliente!\n");
out.close();//aqui eu fecho out pra poder criptar.
in.close();// //
ar_crip.delete();
fecharConexao(client);
}catch (IOException e) {
ServidorJFrame.informarEvento("Erro no Envio!\n");
}
}
private void fecharConexao(Socket client){
try{
client.close();
ServidorJFrame.informarEvento("Conexão fechada com o cliente!\n");
}catch(IOException e){
ServidorJFrame.informarEvento("Erro ao tentar fechar conexão!\n");
}
}//fim do FecharConexao
}//... 1 fim do Servidor Thread