-1

可能重复:
用于定时登录的客户端/服务器 - 我的代码很疯狂

请看一下这个客户端服务器程序并帮助我让它们工作。只有在服务器检查客户端发送的登录并在登录检查后发回“OK”后,程序才应启动计时器。请帮助我,这些代码做了一些疯狂的事情,例如:当我单击客户端按钮“CONNETTI”(CONNECT)时,第二个客户端启动......我不知道为什么也不知道如何!请帮帮我,谢谢!!!

--- 客户项目 ---

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----->"+(confermaLogin));
                          if(confermaLogin.equals("OK"))
                          {
                             //if (clientSocket != null && out != null && in != null) {
                               Tempo tempo = new Tempo();
                             final Date data = tempo.dataCompleta;
                             startTime = System.currentTimeMillis();
                                timer.start();
                                buttonLogin.setEnabled(false);
                                buttonLogout.setEnabled(true);                      
                             status.setText("<html>Log In Effettuato con Successo! <br>Data e Ora:<br>"+ data+"</html>");

                      // }  
                          }
                          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("<html>Log Out Effettuato con Successo! <br>Data e Ora:<br>"+ data+"</html>");

            }
        });

        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

--- 服务器项目 ----

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:---->"+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;   
   }


}
4

1 回答 1

1

一个常见的错误是混合文本和二进制流,例如写入一个但读取另一个。

在您的情况下,您将二进制写入(服务器端)与文本读取(客户端)混合在一起,这肯定会令人困惑。此外,您在客户端上正确写入文本,但缓冲它不太可能有用,因为您必须每次都刷新它以确保它被发送。

我建议您使用 BufferedReader 和 PrintWriter 以及尽可能少的其他内容。BTW PrintWriter 不会抛出不理想的 IOException ,您必须checkError()查看它是否失败。:|

于 2012-12-18T11:28:09.350 回答