Introdução às Redes de Computadores/Transferência de arquivos

RFC editar

Resumo editar

O projeto consiste de um cliente FTP que se conecta a um servidor FTP qualquer caracterizado pelo seu host e porta com seu usuário e senha cadastrados no servidor ou como usuário anônimo, caso o servidor permita esse tipo de acesso.

O usuário pode fazer upload de arquivos quaisquer para o servidor, bastando apenas indicar uma pasta disponível no servidor onde ele tenha acesso à escrita de arquivos. O projeto também prevê que ao conectar ao servidor o mesmo retorna uma pasta disponível para o usuário no campo correspondente, que pode ser alterado pelo usuário de acordo com a pasta desejada.

Ao usuário cabe apenas selecionar o tipo de arquivo à fazer upload de forma à melhorar o desempenho na transferência e evitar que arquivo se corrompa. Os tipos possíveis são ASCII para arquivos de texto neste formato e binário para arquivos em geral.

Também é exibido ao usuário um log de suas operações, numa interface basta amigável e intuitiva.

O projeto foi implementado utilizando a IDE NetBeans versão 6.0.1 e a versão 1.6.0_7 da JRE.

Abaixo podemos ver a tela que o usuário visualizará ao inicializar o programa ClienteFTP. E aqui podemos visualizar uma printscreen que demonstra o funcionamento do programa num servidor FTP local.

Ficheiro:Clienteftp.jpg

Definições editar

Listamos aqui alguns termos e definições que seriam necessários para um usuário qualquer entender nosso programa e poder utilizá-lo, independente de seu nível de conhecimento do assunto:

Host/IP: identificação de uma rede ou de uma máquina conectada a uma rede. No nosso projeto é necessário indicá-lo para se conectar ao servidor FTP desejado.

Porta: geralmente 21 para conexões FTP.

Usuário: nome de usuário fornecido pelo servidor FTP para conexão com o mesmo.

Senha: senha correspondente a um determinado usuário para acesso a alguma aplicação. No projeto é a senha fornecida pelo servidor FTP para conexão com o mesmo.

Arquivo ASCII: arquivos geralmente com extensão .txt que usam codificação padrão ASCII.

Arquivo binário: arquivos em geral (músicas, imagens, vídeos, etc) que usam codificação binária.

Upload: transferência de dados de uma máquina local para um servidor.

Log: histórico de operações realizadas.

FTP: file transfer protocol (protocolo de transferência de arquivos).

Servidor: uma máquina, conjunto de máquinas ou mesmo um software que fornece qualquer tipo de serviço a um determinado cliente ou conjunto de clientes.

Cliente: uma máquina, conjunto de máquinas, ou mesmo um software que usufrui de qualquer tipo de serviço fornecido por um servidor.

Falhas e problemas de segurança atuais editar

Como não há qualquer tipo de criptografia, a segurança da conexão estabelecida com o servidor FTP é mínima.

Entre alguns bugs que podemos notar está um que encontramos no método retornaDir da classe ClienteFTP, que não está retornando um diretório do servidor FTP para que o usuário possa fazer upload. Fizemos testes com alguns servidores externos e não funcionou. Funcionou apenas com um servidor FTP local que montamos para teste. Ainda não tivemos tempo de investigar a fundo essa situação.

Melhorias futuras editar

Entre as melhorias futuras possíveis, destacamos a implementação de um cliente FTP completo, onde seria possível visualizar arquivos, pastas e subpastas contidos no servidor FTP, e fazer download dos mesmos.

Devido as circunstâncias e à complexidade do mesmo, não nos foi possível implementar esse tipo de cliente FTP que desejaríamos. Mas fica aqui registrado a nossa intenção de faze-lo e com isso aprender mais a respeito tanto do protocolo FTP de transferência de dados quanto das opções (classes) que a linguagem Java nos oferece para implementação do mesmo.

Código-fonte do projeto editar

Classe ClienteFTP editar

     /*
      * Esta classe implementa um cliente FTP Java.
      * Entre suas funcionalidades está conectar a um servidor
      * FTP qualquer e fazer upload de arquivos para o mesmo.
      */
     
     /**
      *
      * @author Marcus Vinícius Gonzaga Ferreira
      * @author Lucas Reinehr Andrade
      * @author Pedro César da Silva Álvares
      */
     
     import java.io.*;
     import java.net.*;
     import java.util.*;
     
     public class ClienteFTP {
         
         
         /**
          * Cria uma instância do ClienteFTP.
          */
         
         public ClienteFTP() {
         }
         
         
         /**
          * Conecta a um servidor FTP pela porta porta padrão 21
          * e faz logon como anonymous/anonymous.
          */
         
         public synchronized void conectar(String host) throws IOException {
             conectar(host, 21);
         }
         
         
         /**
          * Conecta a um servidor FTP especificado e faz logon como
          * anonymous/anonymous.
          */
         
         public synchronized void conectar(String host, int porta) throws IOException {
             conectar(host, porta, "anonymous", "anonymous");
         }
         
         
         /**
          * Conecta a um servidor FTP especificado e faz logon com
          * o usuário e a senha fornecida.
          */
         
         public synchronized void conectar(String host, int porta, String usuario, String senha) throws IOException {
             if (socket != null) {
                 throw new IOException("ClienteFTP já está conectado. Desconecte primeiro.");
             }
             socket = new Socket(host, porta);
             reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
             String resposta = readLine();
             if (!resposta.startsWith("220 ")) {
                 throw new IOException("ClienteFTP recebeu uma resposta inesperada ao conectar no servidor FTP: " + resposta);
             }
             sendLine("USER " + usuario);
             resposta = readLine();
             if (!resposta.startsWith("331 ")) {
                 throw new IOException("ClienteFTP recebeu uma resposta inesperado ao conectar com o usuario: " + resposta);
             }
             sendLine("PASS " + senha);
             resposta = readLine();
             if (!resposta.startsWith("230 ")) {
                 throw new IOException("ClienteFTP nao pode conectar com a senha fornecida: " + resposta);
             }        
         }
         
         /**
          * Desconecta do servidor FTP.
          */
         
         public synchronized void desconectar() throws IOException {
             try {
                 sendLine("QUIT");
             }
             finally {
                 socket = null;
             }
         }
             
         /**
          * Retorna o diretório correspondente ao servidor FTP que
          * o cliente está conectado.
          */
         public synchronized String retornaDir() throws IOException {
             sendLine("PWD");
             String diretorio = null;
             String resposta = readLine();
             if (resposta.startsWith("257 ")) {
                 int firstQuote = resposta.indexOf('\"');
                 int secondQuote = resposta.indexOf('\"', firstQuote + 1);
                 if (secondQuote > 0) {
                     diretorio = resposta.substring(firstQuote + 1, secondQuote);
                 }
             }
             return diretorio;
         }
     
         /**
          * Muda o diretório correspondente ao servidor FTP que o
          * cliente está conectado.
          * Retorna verdadeiro se foi mudado o diretório.
          */
         
         public synchronized boolean mudarDir(String diretorio) throws IOException {
             sendLine("CWD " + diretorio);
             String resposta = readLine();
             return (resposta.startsWith("250 "));
         }
             
         /**
          * Faz upload de um arquivo para o servidor FTP que o cliente
          * está conectado.
          * Retorna verdadeiro se o upload foi feito corretamente.
          */
         
         public synchronized boolean upload(File arquivo) throws IOException {
             if (arquivo.isDirectory()) {
                 throw new IOException("ClienteFTP não pode fazer upload de uma pasta");
             }        
             String nomeArquivo = arquivo.getName();
             return upload(new FileInputStream(arquivo), nomeArquivo);
         }   
         
         /**
          * Faz upload de um arquivo para o servidor FTP que o cliente
          * está conectado.
          * Retorna verdadeiro se o upload foi feito corretamente.
          */
         
         public synchronized boolean upload(InputStream inputStream, String nomeArquivo) throws IOException {
             BufferedInputStream input = new BufferedInputStream(inputStream);        
             sendLine("PASV");
            String resposta = readLine();
             if (!resposta.startsWith("227 ")) {
                 throw new IOException("ClienteFTP não pôde requisitar modo passivo: " + resposta);
             }        
             String ip = null;
             int porta = -1;
             int opening = resposta.indexOf('(');
             int closing = resposta.indexOf(')', opening + 1);
             if (closing > 0) {
                 String dataLink = resposta.substring(opening + 1, closing);
                 StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
                 try {
                     ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken();
                     porta = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
                 }
                 catch (Exception e) {
                     throw new IOException("ClienteFTP recebeu informação corrompida: " + resposta);
                 }
             }        
             sendLine("STOR " + nomeArquivo);        
             Socket dataSocket = new Socket(ip, porta);        
             resposta = readLine();
             if (!resposta.startsWith("150 ")) {
                 throw new IOException("ClienteFTP não foi permitido fazer upload do arquivo: " + resposta);
             }        
             BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
             byte[] buffer = new byte[4096];
             int bytesRead = 0;
             while ((bytesRead = input.read(buffer)) != -1) {
                 output.write(buffer, 0, bytesRead);
             }
             output.flush();
             output.close();
             input.close();        
             resposta = readLine();
             return resposta.startsWith("226 ");
         }
     
         /**
          * Seta o modo binário para fazer upload de arquivos.
          */
         
         public synchronized boolean binario() throws IOException {
             sendLine("TYPE I");
             String resposta = readLine();
             return (resposta.startsWith("200 "));
         }
         
         /**
          * Seta o modo ASCII para fazer upload de arquivos.
          */
         public synchronized boolean ascii() throws IOException {
             sendLine("TYPE A");
             String resposta = readLine();
             return (resposta.startsWith("200 "));
         }
             
         /**
          * Envia comando ao servidor FTP.
          */
         
         private void sendLine(String comando) throws IOException {
             if (socket == null) {
                 throw new IOException("ClienteFTP não está conectado.");
             }
             try {
                 writer.write(comando + "\r\n");
                 writer.flush();
                 if (DEBUG) {
                     System.out.println("> " + comando);
                 }
             }
             catch (IOException e) {
                 socket = null;
                 throw e;
             }
         }
         
         /**
          * Lê comando do servidor FTP.
          */
         
         private String readLine() throws IOException {
             String comando = reader.readLine();
             if (DEBUG) {
                 System.out.println("< " + comando);
             }
             return comando;
         }
         
         /**
          * Declaração de variáveis.
          */
         
         private Socket socket = null;
         private BufferedReader reader = null;
         private BufferedWriter writer = null;
         private static boolean DEBUG = false;
     }

Classe JanelaPrincipal editar

     /*
      * Esta classe implementa a interface gráfica do programa
      * para iniciar suas funcionalidades.
      */
     
     /**
      *
      * @author Marcus Vinícius Gonzaga Ferreira
      * @author Lucas Reinehr Andrade
      * @author Pedro César da Silva Álvares
      */
     
     import java.io.*;
     import java.io.File.*;
     import java.awt.*;
     import java.awt.event.*;
     import javax.swing.*;
     
     public class JanelaPrincipal extends javax.swing.JFrame {
         
         /**
          * Cria um objeto ClienteFTP.
          */
         
         private ClienteFTP cliente = new ClienteFTP();
         
         /** 
          * Cria uma nova instância JanelaPrincipal.
          */
         
         public JanelaPrincipal() {
             initComponents();
         }
         
         /** 
          * Inicializa a interface gráfica.
          */
         
         // <editor-fold defaultstate="collapsed" desc="Generated Code">
         private void initComponents() {
     
             buttonGroup1 = new javax.swing.ButtonGroup();
             jTextField1 = new javax.swing.JTextField();
             jTextField2 = new javax.swing.JTextField();
             jTextField3 = new javax.swing.JTextField();
             jButton1 = new javax.swing.JButton();
             jPasswordField1 = new javax.swing.JPasswordField();
             jLabel1 = new javax.swing.JLabel();
             jLabel2 = new javax.swing.JLabel();
             jLabel3 = new javax.swing.JLabel();
             jLabel4 = new javax.swing.JLabel();
             jButton2 = new javax.swing.JButton();
             jButton3 = new javax.swing.JButton();
             jScrollPane1 = new javax.swing.JScrollPane();
             jTextArea1 = new javax.swing.JTextArea();
             jRadioButton1 = new javax.swing.JRadioButton();
             jRadioButton2 = new javax.swing.JRadioButton();
             jLabel5 = new javax.swing.JLabel();
             jLabel6 = new javax.swing.JLabel();
             jTextField4 = new javax.swing.JTextField();
             jLabel7 = new javax.swing.JLabel();
             jMenuBar1 = new javax.swing.JMenuBar();
             jMenu1 = new javax.swing.JMenu();
             jMenuItem1 = new javax.swing.JMenuItem();
             jMenuItem2 = new javax.swing.JMenuItem();
             jMenu2 = new javax.swing.JMenu();
             jMenuItem3 = new javax.swing.JMenuItem();
             jMenuItem4 = new javax.swing.JMenuItem();
             jMenuItem5 = new javax.swing.JMenuItem();
     
             buttonGroup1.add(jRadioButton1);
             buttonGroup1.add(jRadioButton2);
     
             setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
             setTitle("ClienteFTP");
             setResizable(false);
     
             jTextField2.setText("21");
     
             jTextField3.setText("anonymous");
     
             jButton1.setText("Conectar ao servidor FTP");
             jButton1.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jButton1ActionPerformed(evt);
                 }
             });
     
             jPasswordField1.setText("anonymous");
     
             jLabel1.setText("Host/IP:");
     
             jLabel2.setText("Porta:");
     
             jLabel3.setText("Usuário:");
     
             jLabel4.setText("Senha:");
     
             jButton2.setText("Desconectar");
             jButton2.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jButton2ActionPerformed(evt);
                 }
             });
     
             jButton3.setText("Fazer upload de arquivo para servidor FTP");
             jButton3.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jButton3ActionPerformed(evt);
                 }
             });
     
             jTextArea1.setColumns(20);
             jTextArea1.setEditable(false);
             jTextArea1.setRows(5);
             jScrollPane1.setViewportView(jTextArea1);
     
             jRadioButton1.setSelected(true);
             jRadioButton1.setText("Arquivo binário (imagens, vídeos, etc)");
             jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jRadioButton1ActionPerformed(evt);
                 }
             });
     
             jRadioButton2.setText("Arquivo ASCII");
             jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jRadioButton2ActionPerformed(evt);
                 }
             });
     
             jLabel5.setText("Selecione o tipo de arquivo para fazer upload:");
     
             jLabel6.setText("Digite aqui a pasta em que deseja fazer upload no servidor FTP:");
     
             jTextField4.setText("pasta\\subpasta");
     
             jLabel7.setText("Log de operações:");
     
             jMenu1.setText("Menu");
     
             jMenuItem1.setText("Sobre");
             jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jMenuItem1ActionPerformed(evt);
                 }
             });
             jMenu1.add(jMenuItem1);
     
             jMenuItem2.setText("Fechar");
             jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jMenuItem2ActionPerformed(evt);
                 }
             });
             jMenu1.add(jMenuItem2);
     
             jMenuBar1.add(jMenu1);
     
             jMenu2.setText("Ferramentas");
     
             jMenuItem3.setText("Conectar");
             jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jMenuItem3ActionPerformed(evt);
                 }
             });
             jMenu2.add(jMenuItem3);
     
             jMenuItem4.setText("Desconectar");
             jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jMenuItem4ActionPerformed(evt);
                 }
             });
             jMenu2.add(jMenuItem4);
     
             jMenuItem5.setText("Fazer upload");
             jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
                 public void actionPerformed(java.awt.event.ActionEvent evt) {
                     jMenuItem5ActionPerformed(evt);
                 }
             });
             jMenu2.add(jMenuItem5);
     
             jMenuBar1.add(jMenu2);
     
             setJMenuBar(jMenuBar1);
     
             javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
             getContentPane().setLayout(layout);
             layout.setHorizontalGroup(
                 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addGroup(layout.createSequentialGroup()
                     .addContainerGap()
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                         .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                         .addComponent(jRadioButton2)
                         .addComponent(jRadioButton1)
                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                             .addGroup(layout.createSequentialGroup()
                                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                     .addComponent(jLabel1)
                                     .addComponent(jLabel2)
                                     .addComponent(jLabel3)
                                     .addComponent(jLabel4))
                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                     .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING)
                                     .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
                                     .addComponent(jPasswordField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                                     .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)))
                             .addComponent(jLabel5)
                             .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                             .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE))
                         .addComponent(jLabel6)
                         .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                         .addComponent(jLabel7)
                         .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE))
                     .addContainerGap())
             );
             layout.setVerticalGroup(
                 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addGroup(layout.createSequentialGroup()
                     .addContainerGap()
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                         .addComponent(jLabel1)
                         .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                         .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                         .addComponent(jLabel2))
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                         .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                         .addComponent(jLabel3))
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                         .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                         .addComponent(jLabel4))
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jButton1)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jButton2)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jLabel5)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jRadioButton1)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jLabel6)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jButton3)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jLabel7)
                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                     .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
             );
     
             pack();
         }// </editor-fold>
     
         /**
          * Implementa funcionalidade do botão 'Conectar'.
          */
         
         private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
             String host = this.jTextField1.getText();
             int porta = Integer.parseInt(this.jTextField2.getText());
             String usuario = this.jTextField3.getText();
             String senha = this.jPasswordField1.getText();
             try {
                 cliente.conectar(host, porta, usuario, senha);
                 JOptionPane.showMessageDialog(null, "Conectado");
                 jTextArea1.append("Conectado ao servidor " + host + "\n");
                 try{
                     jTextField4.setText(cliente.retornaDir());
                 }
                 catch(IOException x){
                 }  
             }
             catch (IOException x) {
                 JOptionPane.showMessageDialog(null, "Erro ao efetuar login \nVerifique os dados e tente novamente");
                 jTextArea1.append("Erro ao efetuar login\n" + x + "\n");
             }
         }                                        
     
         /**
          * Implementa funcionalidade do botão 'Fazer upload'.
          */
         
         private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
             JFileChooser fc = new JFileChooser();
             int res = fc.showOpenDialog(JanelaPrincipal.this);
             try {
                 if(res == JFileChooser.APPROVE_OPTION){
                     String arquivo = fc.getSelectedFile().toString();
                     cliente.mudarDir(this.jTextField4.getText());
                     cliente.upload(new File(arquivo));
                     JOptionPane.showMessageDialog(null, "Voce selecionou o arquivo: " + fc.getSelectedFile().getName());
                     jTextArea1.append("Arquivo salvo: " + fc.getSelectedFile().getName() + "\n");
                 }
                 else
                     JOptionPane.showMessageDialog(null, "Voce nao selecionou nenhum arquivo\nTente novamente");
             }
             catch (IOException x) {
                 JOptionPane.showMessageDialog(null, "Erro ao fazer upload");
                 jTextArea1.append("Erro ao fazer upload\n" + x + "\n");
             }
         }                                        
     
         /**
          * Implementa funcionalidade do botão 'Desconectar'.
          */
         
         private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
             try {
                 cliente.desconectar();
                 JOptionPane.showMessageDialog(null, "Desconectado");
                 jTextArea1.append("Desconectado\n");
                 }
             catch (IOException x) {
                 JOptionPane.showMessageDialog(null, "Erro ao desconectar");
                 jTextArea1.append("Erro ao desconectar\n" + x + "\n");
                 }
         }                                        
     
         /**
          * Seta o modo ASCII quando selecionado.
          */
         
         private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                              
             try {
                 cliente.ascii();
                 }
             catch(IOException x){
                 }
         }                                             
     
         /**
          * Seta o modo binário quando selecionado.
          */
         
         private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
             try{
                 cliente.binario();
                 }
             catch(IOException x){
                 }
         }                                             
     
         /**
          * Implementa funcionalidade do submenu 'Sobre'.
          */
         
         private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
             JOptionPane.showMessageDialog(null, "**Projeto de Redes de Computadores**              \n\nProfessor:\n-Marcelo Akira\n\nGrupo:\n-Marcus Vinicius Gonzaga Ferreira \n-Pedro César da Silva Álvares \n-Lucas Reinehr de Andrade\n");
         }
     
         /**
          * Implementa funcionalidade do submenu 'Fechar'.
          */
         
         private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
             System.exit(0);
         }
     
         /**
          * Implementa funcionalidade do submenu 'Conectar'.
          */
         
         private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
             jButton1ActionPerformed(null);
         }
     
         /**
          * Implementa funcionalidade do submenu 'Desconectar'.
          */
         
         private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {
             jButton2ActionPerformed(null);
         }
     
         /**
          * Implementa funcionalidade do submenu 'Fazer upload'.
          */
         
         private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {
             jButton3ActionPerformed(null);
         }
         
         /**
          * Chama a interface gráfica.
          */
         
         public static void main(String args[]) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                 public void run() {
                     new JanelaPrincipal().setVisible(true);
                     }
                 }
             );
             }
         
         // Variables declaration - do not modify
         private javax.swing.ButtonGroup buttonGroup1;
         private javax.swing.JButton jButton1;
         private javax.swing.JButton jButton2;
         private javax.swing.JButton jButton3;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JLabel jLabel6;
         private javax.swing.JLabel jLabel7;
         private javax.swing.JMenu jMenu1;
         private javax.swing.JMenu jMenu2;
         private javax.swing.JMenuBar jMenuBar1;
         private javax.swing.JMenuItem jMenuItem1;
         private javax.swing.JMenuItem jMenuItem2;
         private javax.swing.JMenuItem jMenuItem3;
         private javax.swing.JMenuItem jMenuItem4;
         private javax.swing.JMenuItem jMenuItem5;
         private javax.swing.JPasswordField jPasswordField1;
         private javax.swing.JRadioButton jRadioButton1;
         private javax.swing.JRadioButton jRadioButton2;
         private javax.swing.JScrollPane jScrollPane1;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JTextField jTextField1;
         private javax.swing.JTextField jTextField2;
         private javax.swing.JTextField jTextField3;
         private javax.swing.JTextField jTextField4;
         // End of variables declaration
         
     }

Classe Main editar

     /*
      * Esta classe chama a interface gráfica do programa
      * para iniciar suas funcionalidades.
      */
     
     /**
      *
      * @author Marcus Vinícius Gonzaga Ferreira
      * @author Lucas Reinehr Andrade
      * @author Pedro César da Silva Álvares
      */
     
     public class Main {
     
         /**
          * @param args the command line arguments
          */
         
         public static void main(String[] args) {
             new JanelaPrincipal().setVisible(true);
         }
     }

Diagramas de mensagem editar

Diagramas FSM editar