Alterar dados cliente/servidor-socket

0 respostas
E

queridos a algum tempo preguntei aqui como alterar dados em um painel- não tinha nada em mente.
agora volto com algum código e já agradeço a ajuda.

fiz essa tela para esperar dados-servidor.
me basiei em exemplos daqui do GUJ. mas não consigo alterar os dados da tela servidor

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

/*
 * server.java
 *
 * Created on 04/12/2010, 13:42:25
 */

/**
 *
 * @author dani
 */

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
    import java.io.*;
    import java.net.*;    
import java.text.DecimalFormat;
    import java.util.*;
   

public class server extends javax.swing.JFrame {
     private DatagramPacket sendPacket, receivePacket;
     private DatagramSocket socket;
     int hh,mm,ss,h;
     Calendar CalendarHora;
     DecimalFormat formato;


    /** Creates new form server */
    public server() {
        initComponents();
   // javax.swing.Timer time1 = new javax.swing.Timer(1000,tarefa);
   /// time1.start();
        try
         {
            socket = new DatagramSocket(5000);
        }
        catch (SocketException socketException)
        {
          socketException.printStackTrace();
          System.exit(1);
     }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        tf_abertofechado = new javax.swing.JTextField();
        tf_senha = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tf_balcao = new javax.swing.JTextField();
        tf_tipo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        displayArea = new javax.swing.JTextArea();
        rt_hora = new javax.swing.JLabel();

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

        tf_abertofechado.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
        tf_abertofechado.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tf_abertofechado.setText("ABERTO");
        tf_abertofechado.setEnabled(false);

        tf_senha.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        tf_senha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tf_senha.setEnabled(false);

        jLabel1.setText("SENHA");

        jLabel4.setText("BALCÃO");

        tf_balcao.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        tf_balcao.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tf_balcao.setEnabled(false);

        tf_tipo.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        tf_tipo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tf_tipo.setEnabled(false);

        jLabel2.setText("TIPO");

        jLabel3.setText("MENSAGENS");

        jScrollPane1.setEnabled(false);

        displayArea.setColumns(20);
        displayArea.setRows(5);
        jScrollPane1.setViewportView(displayArea);

        rt_hora.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 1, 36)); // NOI18N
        rt_hora.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        rt_hora.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 764, Short.MAX_VALUE)
                            .addComponent(jLabel3)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(tf_abertofechado, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(rt_hora, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(51, 51, 51)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(tf_balcao, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 294, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(tf_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(rt_hora, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
                    .addComponent(tf_abertofechado, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(100, 100, 100)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(tf_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_balcao, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

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

     //espera que os pacotes cheguem e, depois, exibe os dados e ecoa o pacote p/ o cliente
      public void waitForPackets()
      {
         while (true)
         {
            //recebe o pacote, exibe o conteudo e ecoa p/ o cliente
            try
            {
               byte data[] = new byte[100];
               receivePacket = new DatagramPacket (data,data.length);

               //espera o pacote
               socket.receive (receivePacket);

               //processa o pacote
               displayPacket();

               //ecoa as informacoes do pacote de volta p/ o cliente
               sendPacketToClient();
            }
            catch (IOException ioException)
            {
               displayArea.append(ioException.toString() + "\n");
               ioException.printStackTrace();
            }
         }
      }
  ActionListener tarefa = (new ActionListener(){
            public void actionPerformed(ActionEvent e){
            HORAS();

            }
    });

    private String formatar(int num){
        formato = new DecimalFormat("00");
        return formato.format(num);
        }
    private void HORAS(){

        CalendarHora = Calendar.getInstance();
        hh = CalendarHora.get(Calendar.HOUR_OF_DAY);
        mm = CalendarHora.get(Calendar.MINUTE);
        ss = CalendarHora.get(Calendar.SECOND);
        formato = new DecimalFormat("00");
        rt_hora.setText(formatar(hh%24)+":"+formatar(mm)+":"+formatar(ss));
        }

      //exibe conteudo do pacote
      private void displayPacket()
      {

         //É aqui que os dados sao recebidos em bytes, convertidos p/ string e jogados nos
         //seus campos pelo Token
         
         String SNome="",SData="",SHora="";
         String dados = new String(receivePacket.getData(),0,receivePacket.getLength());
         String auxToken = "";
         String senha = "";
         String balcao = "";
         int iCont=0;
         StringTokenizer tokens = new StringTokenizer(dados);

         while (tokens.hasMoreTokens())
        {

            SNome = tokens.nextToken();
            SData = tokens.nextToken();
            SHora = tokens.nextToken();
            senha = tokens.nextToken();
            balcao = tokens.nextToken();

         }
    
          displayArea.append("Nome: " + SNome +"\nData: " + SData + "\nHora: " + SHora +" \nSenha"+senha+"\n"+balcao);
         tf_senha.setText(senha);
         tf_balcao.setText(balcao);

    }


     //ecoa pacote p/ o cliente
     private void sendPacketToClient() throws IOException
     {
        displayArea.append("\n\nEcho data to client...");

        //cria pacote p/ enviar
      

        String message = "MENSAGEM ENTREGUE COM SUCESSO!!!";//event.getActionCommand();
          byte data[] = message.getBytes();
        sendPacket = new DatagramPacket(data,data.length,receivePacket.getAddress(),receivePacket.getPort());
        socket.send(sendPacket);

        displayArea.append("Packet sent\n\n================================");
        displayArea.setCaretPosition(displayArea.getText().length());
     }


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

    // Variables declaration - do not modify
    private javax.swing.JTextArea displayArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel rt_hora;
    private javax.swing.JTextField tf_abertofechado;
    private javax.swing.JTextField tf_balcao;
    private javax.swing.JTextField tf_senha;
    private javax.swing.JTextField tf_tipo;
    // End of variables declaration

}

e essa cliente

import java.io.*;
   import java.net.*;
   import java.awt.*;
   import java.awt.event.*;
  import java.util.*;

  // Java extension packages
  import javax.swing.*;

  public class Client1 extends JFrame {
     private JTextField enterField;
     private JTextArea displayArea;
     private DatagramPacket sendPacket, receivePacket;
     private DatagramSocket socket;

     // set up GUI and DatagramSocket
     public Client1()
     {
        super( "Client" );

        Container container = getContentPane();

        enterField = new JTextField( "   " );



        enterField.addActionListener(

           new ActionListener() {

              // create and send a packet
              public void actionPerformed( ActionEvent event )
              {
                 // create and send packet
                 try
              {
                    displayArea.append("\nSending packet containing: " + event.getActionCommand() + "\n" );

                    // get message from textfield and convert to
                    // array of bytes
                   String senha =String.valueOf(enterField.getText());
                   String balcao= String.valueOf(5);

                    String Nome="nome",Hora="00:00";
                String Data="00/00/0000";
                String message = /*event.getActionCommand()+*/ Nome + " " + Data + " "+ Hora+" "+senha +""+ balcao;
                    byte data[] = message.getBytes();

                //TOKENS
                /*String stringToTokenize = event.getActionCommand();
                StringTokenizer tokens = new StringTokenizer(stringToTokenize);*/

                    // create sendPacket
                    sendPacket = new DatagramPacket(data,data.length, InetAddress.getByName("localhost"), 5000 );

                    // send packet
                    socket.send( sendPacket );

                    displayArea.append( "Packet sent\n" );
                    displayArea.setCaretPosition(displayArea.getText().length() );
                 }

                 // process problems creating or sending packet
                 catch ( IOException ioException ) {
                    displayArea.append(
                       ioException.toString() + "\n" );
                    ioException.printStackTrace();
                 }

              }  // end actionPerformed

           }  // end anonymous inner class

        ); // end call to addActionListener

        container.add( enterField, BorderLayout.NORTH );

        displayArea = new JTextArea();
        container.add( new JScrollPane( displayArea ), BorderLayout.CENTER );

        setSize( 400, 300 );
        setVisible( true );

        // create DatagramSocket for sending and receiving packets
        try
       {
           socket = new DatagramSocket();
        }

        // catch problems creating DatagramSocket
        catch( SocketException socketException )
       {
           socketException.printStackTrace();
           System.exit( 1 );
        }

     }  // end Client constructor

     // wait for packets to arrive from Server,
     // then display packet contents
     public void waitForPackets()
     {
        // loop forever
       while ( true )
       {
          // receive packet and display contents
          try
         {

             // set up packet
             byte data[] = new byte[ 100 ];
              receivePacket = new DatagramPacket( data, data.length );

              // wait for packet
              socket.receive( receivePacket );

              // display packet contents
              displayPacket();
           }

           // process problems receiving or displaying packet
           catch( IOException exception )
         {
              displayArea.append( exception.toString() + "\n" );
              exception.printStackTrace();
           }

        }  // end while

     }  // end method waitForPackets

     // display contents of receivePacket
     private void displayPacket()
     {
        displayArea.append( "\nPacket received:" +
           "\nFrom host: " + receivePacket.getAddress() +
           "\nHost port: " + receivePacket.getPort() +
           "\nLength: " + receivePacket.getLength() +
           "\nContaining:\n\t" +
           new String( receivePacket.getData(), 0, receivePacket.getLength() ) );

        displayArea.setCaretPosition(displayArea.getText().length() );
     }

     // execute application
     public static void main( String args[] )
   {
        Client1 application = new Client1();

        application.setDefaultCloseOperation(
           JFrame.EXIT_ON_CLOSE );

        application.waitForPackets();
     }

 }  // end class Client
Criado 4 de dezembro de 2010
Respostas 0
Participantes 1