Java's Client / Server has imperfect connection and not working communications
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/13929985/client-server-for-a-timered-login-my-codes-are-creazy">Client / Server for a Timered Login - My codes are creazy</a>  </p>
</blockquote>



<p>1 down vote favorite</p>

<p>please, take a look at this CLient Server Programs and help me to let them work. The program should start a timer only after that the Server check the login sent by client and send back an "OK" after a log-in check. Please help me, these codes do something crazy, for example: a second client starts when I click the Client Button "CONNETTI" (CONNECT)... and I don't know why neither how! please help me, thanx!!!</p>

<p>--- CLIENT PROJECT ---</p>

<pre><code>enter code here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;


public class Cronometro{
    private JFrame frame;
    private JLabel labelTime;
    private JPanel panelButtons;
    private JButton buttonLogin;
    private JButton buttonLogout;
   JTextField username = new JTextField(15);
   JTextField password = new JTextField(15);
   JTextField telefono = new JTextField(6);
   JLabel status = new JLabel("Server Disconnesso");
   JLabel empty = new JLabel();
   JLabel title = new JLabel ("LudecaLog-In");
   JLabel nameLabel = new JLabel ("Nome Utente: ");
   JLabel passLabel = new JLabel ("Password: ");
   JLabel telLabel = new JLabel ("Telefono: ");
    private Timer timer;
    private long startTime;

    String rigaTesto;
   // DataInputStream in;
    BufferedReader in ;
    DataOutputStream  out;
    Socket clientSocket;

    public Cronometro ()
    {


        frame = new JFrame ("Cronometro");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setSize (500, 500);

        labelTime = new JLabel ("0:00:00.0");
        labelTime.setFont (new Font ("SansSerif", Font.BOLD, 30));
        labelTime.setHorizontalAlignment (JLabel.CENTER);

        buttonLogin = new JButton ("START");
        buttonLogout = new JButton ("STOP");
        buttonLogout.setEnabled (false);

      title.setForeground(Color.blue);
      title.setHorizontalAlignment(JLabel.CENTER);
      Font titleFont = new Font("Title", Font.CENTER_BASELINE, 50);
      title.setFont(titleFont);

      GridBagConstraints constr = new GridBagConstraints();

        panelButtons = new JPanel (new GridBagLayout());

        constr.gridx=0;
      constr.gridy=2;
      panelButtons.add(nameLabel,constr);
        constr.gridx=1;
      constr.gridy=2;
      panelButtons.add(username,constr);
      constr.gridx=0;
      constr.gridy=4;
      panelButtons.add(passLabel,constr);
      constr.gridx=1;
      constr.gridy=4;
      panelButtons.add(password,constr);
      constr.gridx=0;
      constr.gridy=5;
      panelButtons.add(telLabel,constr);
      constr.gridx=1;
      constr.gridy=5;
      telefono.setHorizontalAlignment(JLabel.LEFT);
      panelButtons.add(telefono,constr);
      constr.gridx=1;
      constr.gridy=8;
      panelButtons.add(empty,constr);
      constr.gridx=1;
      constr.gridy=9;
      panelButtons.add(status,constr);
      constr.gridx=0;
      constr.gridy=10;
        panelButtons.add (buttonLogin,constr);
       constr.gridx=2;
      constr.gridy=10;
       panelButtons.add (buttonLogout,constr);
      frame.setVisible(true);
      frame.add(title,BorderLayout.NORTH);
        frame.add (labelTime, BorderLayout.CENTER);
        frame.add (panelButtons, BorderLayout.SOUTH);


        timer = new Timer (50, new ActionListener () {
            public void actionPerformed (ActionEvent e) {
                long diffTime = System.currentTimeMillis () - startTime;

                int decSeconds = (int) (diffTime % 1000 / 100);
                int seconds = (int) (diffTime / 1000 % 60);
                int minutes = (int) (diffTime / 60000 % 60);
                int hours = (int) (diffTime / 3600000);

                String s = String.format ("%d:%02d:%02d.%d", hours, minutes,
                                          seconds, decSeconds);

                labelTime.setText(s);

            }
        });



        buttonLogin.addActionListener (new ActionListener ()
        {
            public void actionPerformed (ActionEvent e)
            {

            /***************** 1 CONNESSIONE AL SERVER *******/
                      try {
                         clientSocket = new Socket("192.168.42.176",9910);
                         System.out.println("Connessione al Server in atto...");

                         String loginOperatore = new String() ;

                              loginOperatore=(username.getText()+password.getText()+telefono.getText());

                         //apertura stream di input
                          InputStreamReader isr=new InputStreamReader(clientSocket.getInputStream());
                          BufferedReader in=new BufferedReader(isr);

                          //apertura stream di output
                          OutputStreamWriter osw=new OutputStreamWriter(clientSocket.getOutputStream());
                          BufferedWriter bw=new BufferedWriter(osw);
                          PrintWriter out=new PrintWriter(bw,true);

                          //invio della stringa al server
                          out.println(loginOperatore.toString());
                          status.setText("Connesso al Server, controllo la Login");


                          String confermaLogin = new String();
                          System.out.println(confermaLogin=in.readLine());
                          System.out.println("ciao-----&gt;"+(confermaLogin));
                          if(confermaLogin.equals("OK"))
                          {
                             //if (clientSocket != null &amp;&amp; out != null &amp;&amp; in != null) {
                               Tempo tempo = new Tempo();
                             final Date data = tempo.dataCompleta;
                             startTime = System.currentTimeMillis();
                                timer.start();
                                buttonLogin.setEnabled(false);
                                buttonLogout.setEnabled(true);                      
                             status.setText("&lt;html&gt;Log In Effettuato con Successo! &lt;br&gt;Data e Ora:&lt;br&gt;"+ data+"&lt;/html&gt;");

                      // }  
                          }
                          else if (confermaLogin.equals("DATI_ERRATI"))
                          {
                             status.setText("ERRORE!!! Dati di Log-In Errata!!");

                          }



                          //chiusura della socket e degli stream
                          clientSocket.close();
                          in.close();
                          bw.close();
                          out.close();                                

                      }
                      catch (UnknownHostException err)
                      {
                           System.err.println("Errore: probelmi di comunicazione");
                       }
                      catch (IOException err1)
                      {
                           System.err.println("Errore: probelmi di comunicazione");
                       }

                      /******************************** 1 FINE CONNESSIONE AL SERVER *******/
            }
        });

        buttonLogout.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e)
            {
                    timer.stop ();
                    buttonLogin.setEnabled (true);
                    buttonLogout.setEnabled (false);
                  Tempo tempo = new Tempo();
                  final Date data = tempo.dataCompleta;
                  status.setText("&lt;html&gt;Log Out Effettuato con Successo! &lt;br&gt;Data e Ora:&lt;br&gt;"+ data+"&lt;/html&gt;");

            }
        });

        frame.setVisible (true);
    }



    public static void main (String[] args)
    {
       SwingUtilities.invokeLater (new Runnable()
                              {
                                  public void run()
                                  {
                                 new Cronometro();
                              }
                            });
    }
}


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class Tempo{
          public int ore,minuti,secondi,giorno,mese,anno;
          public long dataMillis;
          public Date dataCompleta = new Date();

         //costruttore di default
         public Tempo(){        

           GregorianCalendar c =new GregorianCalendar();
           dataCompleta=c.getTime();
           dataMillis=c.getTimeInMillis()/* / (24*60*60*1000)*/;
            ore=c.get(Calendar.HOUR_OF_DAY);
            minuti=c.get(Calendar.MINUTE);
            secondi=c.get(Calendar.SECOND);
            giorno=c.get(Calendar.DAY_OF_MONTH);
            mese=c.get(Calendar.MONTH);
            anno=c.get(Calendar.YEAR);


         }//Tempo
   }//tempo
</code></pre>

<p>--- SERVER PROJECT ----</p>

<pre><code>enter code here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;


public class provaServer{

    private JFrame frame;
    private JPanel panelButtons;
    private JPanel panelSchermiTitolo;

    private JButton buttonConnetti;
    private JButton buttonDisconnetti;
    private JButton buttonSalvaFile;
    private JButton buttonAggiornaSchermi;
    private JButton buttonCreaLogin;
    private TextArea schermoOperatori;
    private TextArea schermoNotifiche;

   JTextField username = new JTextField(15);
   JTextField password = new JTextField(15);
   JTextField telefono = new JTextField(6);
    JLabel status = new JLabel("Server Disconnesso");
   JLabel empty = new JLabel();
   JLabel title = new JLabel ("LudecaLog-In Server");


    String rigaTesto;
   // DataInputStream in;
    BufferedReader in ;
    DataOutputStream  out;





    public provaServer ()
    {


     try {
         Socket clientSocket=null;
        ServerSocket serverSocket=null;
            serverSocket = new ServerSocket(9910);
            clientSocket = serverSocket.accept();
            System.out.println("Server: Sono attivo sulla Rete ");
            //serverSocket.setReuseAddress(true);

            status.setText("Il Server è adesso Attivo sulla Rete");

            BufferedReader in= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            //Stream di output
            DataOutputStream out=new DataOutputStream(clientSocket.getOutputStream());
            String loginOperatore = new String();
            loginOperatore=in.readLine();
            System.out.println("cronServer:----&gt;"+loginOperatore);
            Operatore operatore = new Operatore();
            if(operatore.controllaLogin(loginOperatore)==true)
            {
               out.writeBytes("OK");
            }
            else
            {
               out.writeBytes("DATI_ERRATI");
            }

            System.out.println("Server: Sono attivo sulla Rete ");
            serverSocket.setReuseAddress(true);               
            status.setText("Il Server è adesso Attivo sulla Rete");

         }
         catch (IOException e1) {
            System.out.println(e1);
            System.out.println("Server: Non riesco ad aprire il socket");
         }



        frame = new JFrame ("CronometroServer");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setSize (500, 500);

        //TEXT AREA
        //labelTime = new JLabel ("0:00:00.0");
        //labelTime.setFont (new Font ("SansSerif", Font.BOLD, 30));

        //labelTime.setHorizontalAlignment (JLabel.CENTER);

        buttonSalvaFile = new JButton ("SALVA FILE");
        buttonCreaLogin = new JButton ("CREA LOGIN");
        buttonAggiornaSchermi = new JButton ("AGGIORNA");
        buttonConnetti = new JButton ("CONNETTI");
        buttonDisconnetti = new JButton ("DISCONNETTI");
        //buttonSalvaFile.setEnabled (false);
        //buttonCreaLogin.setEnabled (false);
        //buttonAggiornaSchermi.setEnabled (false);
        //buttonDisconnetti.setEnabled (false);

        schermoOperatori = new TextArea();
        schermoNotifiche = new TextArea();
        schermoOperatori.setEnabled(false);
        schermoNotifiche.setEnabled(false);

      title.setForeground(Color.blue);
      title.setHorizontalAlignment(JLabel.CENTER);
      Font titleFont = new Font("Title", Font.CENTER_BASELINE, 45);
      title.setFont(titleFont);

      GridBagConstraints constr = new GridBagConstraints();

        panelButtons = new JPanel (new GridBagLayout());
        panelSchermiTitolo = new JPanel (new GridBagLayout());

      constr.gridx=0;
      constr.gridy=1;
      panelSchermiTitolo.add(title,constr);
      constr.gridx=0;
      constr.gridy=2;
      panelSchermiTitolo.add(schermoOperatori,constr);
      constr.gridx=0;
      constr.gridy=3;
      panelSchermiTitolo.add(schermoNotifiche,constr);
      constr.gridx=0;
      constr.gridy=4;
      panelSchermiTitolo.add(status,constr);
       constr.gridx=2;
      constr.gridy=0;
       panelButtons.add (buttonDisconnetti,constr);
       constr.gridx=3;
      constr.gridy=0;
       panelButtons.add (buttonAggiornaSchermi,constr);
       constr.gridx=4;
      constr.gridy=0;
       panelButtons.add (buttonSalvaFile,constr);
       constr.gridx=5;
       constr.gridy=0;
       panelButtons.add (buttonCreaLogin,constr);


      frame.add(title,BorderLayout.NORTH);
        frame.add (panelButtons, BorderLayout.SOUTH);
        frame.add (panelSchermiTitolo, BorderLayout.CENTER);
        frame.setVisible(true);


        buttonConnetti.addActionListener (new ActionListener()
        {
            public void actionPerformed (ActionEvent e)
            {


           }
        });

        buttonDisconnetti.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e)
            {
                try {
               clientSocket.close();
                   in.close();
                   out.close(); 
            } catch (IOException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
            }


            }
        });

        frame.setVisible(true);       
    }

    public static void main (String[] args)
    {

       SwingUtilities.invokeLater (new Runnable()
                              {
                                  public void run()
                                  {
                                 new provaServer();
                              }
                            });



    }
}


public class Operatore {

   private String identificatoreLogin = new String ();

   public Operatore()
   {
      identificatoreLogin="rafgrav1106";

   }

   public boolean controllaLogin(String loginInserita)
   {

         System.out.println("oper: "+identificatoreLogin);
            System.out.println("oper:" +loginInserita);
      if(loginInserita.equals(identificatoreLogin))
      {
         return true;
      }
      else
      {
         return false;
      }

   }

   public String getIdentificatoreLogin() {
      return identificatoreLogin;
   }

   public void setIdentificatoreLogin(String identificatoreLogin)
   {
      this.identificatoreLogin=identificatoreLogin;   
   }


}
</code></pre>
