Jump to content
Fórum Script Brasil
  • 0

Protocolo de Redes Java


Alan Correa

Question

Olá pessoal, tenho um tarefa da faculdade para realizar: Criar um protocolo, em java com algumas regras:

1. Desenvolver um aplicativo que receba uma mensagem (“String”) e coloque a

mesma dentro de um protocolo proprietário (Transmissor).

2. Desenvolver um aplicativo que recebe uma mensagem com o protocolo

proprietário e consiga extrair somente a mensagem transmitida (Receptor).

3. A mensagem só pode ter no máximo 16 Mbytes.

4. A transmissão e a recepção podem ser gravadas em arquivo, dessa forma

simulando a comunicação.

5. O endereço do transmissor e do receptor deve ser configurável.

Regras:

Protocolo:

Cabeçalho Mensagem Finalizador Checksum

17 bytes n Bytes 2 bytes 1 byte

Cabeçalho:

Início de cabeçalho = só  0x01

Byte de Sincronia SYN  0x16

Endereço de Origem = 4 bytes

Endereço de Destino = 4 bytes

Tamanho da Mensagem = 2 bytes – 00 até FFFF – tamanho máximo 64 kB

Número de seqüencia = 2 bytes

Tipo de Mensagem = 1 byte

Checksum cabeçalho = 1 byte  calculado

Início da Mensagem = STX  0x02

Finalizador1 = ETX  0x03 (indica o final da mensagem)

Finalizador2 = EOT  0x04 (indica o final da transmissão)

Checksum = 1 byte calculado.

Número de seqüencia  é o campo que indica a ordem de seqüência da mensagem.

Tipo de mensagem  indica qual é o tipo de mensagem que está sendo enviada. Os

tipos de mensagem são os seguintes:

Tipo Significado Caractere

Resposta

Esperada

NRM Mensagem normal 0x00 ACK / NACK

URG Mensagem urgente 0x05 ACK / NACK

ACK Mensagem aceita 0x06 -

PSH

Coloca mensagem no buffer ou confirma

recebimento da mensagem

0x0F ACK / NACK

RST Re-inicializa a comunicação 0x18 ACK / NACK

Segue o que eu já consegui comunicar, porém não está com todas as regras. Alguém pode me ajudar nas alterações?

package servidor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ScreenServidor extends javax.swing.JFrame {
    private ServerSocket Servidor;
    private Socket sComunica;
    private BufferedInputStream is;
    private BufferedOutputStream os;

    /** Creates new form ScreenServidor */
    public ScreenServidor() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        textArea1 = new java.awt.TextArea();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Servidor");

        jButton1.setText("Conecta");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        textArea1.setEditable(false);

        jLabel1.setText("Porta:");

        jTextField1.setText("8000");

        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(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            Servidor = new ServerSocket(Integer.parseInt(jTextField1.getText().toString()));
            sComunica = Servidor.accept();
            if(sComunica != null) {
                is = new BufferedInputStream(sComunica.getInputStream());
                os = new BufferedOutputStream(sComunica.getOutputStream());
                jTextField1.setEnabled(false);
                jButton1.setEnabled(false);
                textArea1.setText("Conectado! "+sComunica.getInetAddress().toString());
                textArea1.append("\n");
                ServidorOuve();
            }
        } catch (IOException ex) {
            Logger.getLogger(ScreenServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    private void ServidorOuve() throws IOException {
        byte[] re = new byte[1024];
        String sLinha = null;
        int nCount=0;
        while(true) {
            try {
                nCount = is.read(re, 0, re.length);
            } catch (IOException ex) {
                Logger.getLogger(ScreenServidor.class.getName()).log(Level.SEVERE, null, ex);
            }
            sLinha = new String(re,0,nCount);
            textArea1.append(sLinha+"\n");
            if(sLinha.contains("quit")) {
                ServidorResponde("Sevidor desconectado!");
                break;
            }
            else if(sLinha.startsWith("dir")) {
                File Dir = new File(".");
                File[] Arquivos = Dir.listFiles();
                for(int i = 0; i < Arquivos.length; i++)
                    ServidorResponde(Arquivos[i].toString());
                ServidorResponde("fim");
            }
            else if(sLinha.startsWith("del")) {
                boolean merda;
                String sDeleteFile = sLinha.substring(4);
                File DelFile = new File(sDeleteFile);
                if(DelFile.delete())
                    ServidorResponde("Arquivo deletado!");
                else
                    ServidorResponde("Arquivo não encontrado!");
            }
            else if(sLinha.startsWith("explorer")) {
                Process p = Runtime.getRuntime().exec("cmd /c "+sLinha);
                ServidorResponde("explorer executado!");
            }
            else if(sLinha.startsWith("cls")) {
                 textArea1.append("Limpando a tela do Cliente!\n");
            }
            else {
                ServidorResponde("Comando inválido!");
            }
        }
        jButton1.setEnabled(true);
        jTextField1.setEnabled(true);
        try {
            is.close();
            os.close();
            sComunica.close();
            textArea1.append("Desconectado!\n");
        } catch (IOException ex) {
            Logger.getLogger(ScreenServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void ServidorResponde(String sResposta){
        byte[] re = new byte[1024];
        re = sResposta.getBytes();
        try {
            os.write(re, 0, sResposta.length());
            os.flush();
        } catch (IOException ex) {
            Logger.getLogger(ScreenServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ScreenServidor().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    private java.awt.TextArea textArea1;
    // End of variables declaration                   

}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ScreenClient.java
 *
 */
package cliente;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 
 */
public class ScreenClient extends javax.swing.JFrame {

    private Socket sComunica;
    private BufferedOutputStream os;
    private BufferedInputStream is;

    /** Creates new form ScreenClient */
    public ScreenClient() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        textArea1 = new java.awt.TextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cliente");
        setResizable(false);

        jButton1.setText("Conecta");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Envia");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Endereço:");

        jTextField1.setText("127.0.0.1");

        jTextField2.setText("8000");

        jLabel2.setText("Porta:");

        jTextField3.setEnabled(false);

        jLabel3.setText("Comando:");

        jLabel4.setText("Resposta:");

        textArea1.setEditable(false);
        textArea1.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 459, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)
                            .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 459, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(16, 16, 16)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addGap(1, 1, 1)
                .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            sComunica = new Socket(jTextField1.getText().toString(), Integer.parseInt(jTextField2.getText().toString()));
            if (sComunica != null) {
                os = new BufferedOutputStream(sComunica.getOutputStream());
                is = new BufferedInputStream(sComunica.getInputStream());
                jButton1.setEnabled(false);
                jTextField1.setEnabled(false);
                jTextField2.setEnabled(false);
                jTextField3.setEnabled(true);
                jButton2.setEnabled(true);
                textArea1.setEnabled(true);
                jTextField3.requestFocus();
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(ScreenClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ScreenClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        byte[] re = new byte[1024];
        re = jTextField3.getText().getBytes();
        try {
            os.write(re, 0, jTextField3.getText().length());
            os.flush();
        } catch (IOException ex) {
            Logger.getLogger(ScreenClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        jTextField3.requestFocus();
        if (jTextField3.getText().contentEquals("dir")) {
            String sLinha = null;
            while (true) {
                sLinha = Recebe();
                textArea1.append(sLinha + "\n");
                if (sLinha.contains("fim")) {
                    break;
                }

            }
        } else if (jTextField3.getText().contains("quit")) {
            textArea1.append("Desconectando ...\n");
            jButton1.setEnabled(true);
            jTextField1.setEnabled(true);
            jTextField2.setEnabled(true);
            jTextField3.setEnabled(false);
            jButton2.setEnabled(false);
            textArea1.setEnabled(false);
            try {
                os.close();
                sComunica.close();
            } catch (IOException ex) {
                Logger.getLogger(ScreenClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (jTextField3.getText().contentEquals("cls")) {
            textArea1.setText(null);
        } else {
            textArea1.append(Recebe() + "\n");
        }
    }                                        

    private String Recebe() {
        byte[] re = new byte[1024];
        String sLinha = null;
        int nCount = 0;

        try {
            nCount = is.read(re);
        } catch (IOException ex) {
            Logger.getLogger(ScreenClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        sLinha = new String(re, 0, nCount);
        return sLinha;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ScreenClient().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private java.awt.TextArea textArea1;
    // End of variables declaration                   
}

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...