Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 15
  1. #1

    [JAVA] - Invio da Client a Server di 4 Variabili: 3 String e 1 Date

    Buonasera,
    Sono un po' arrugginito con la programmazione, e volevo chiedervi una cosa che per voi probabilmente risulterà una banalità:

    Ho scritto un Client ed un Server. Il Client è un semplice Cronometro che registra la login di un utente che si autentifica con Nome, Pass e un codice alfanmerico che identifica la Postazione Telefonica su cui lavora (Tipo Call Center)
    Il client invia queste 3 informazioni concatenandole in unica stringa, il server le confronta con le informazioni di autentificazione che contiene, e a seconda della loro esattezza risponde al Client, che fa partire o meno il cronometro.

    Il programma mi funziona perfettamente, il problema è che non mi interessa inviare la login come unica stringa, ho bisogno che le informazioni vengano inviate separatamente quindi vorrei che il client inviasse consecutivamente prima il nome, subito dopo la pass e infine il codice di postazione telefonica. In ultimo vorrei che se il server rispondesse in modo affermativo all'autentificazione, il client inviasse anche la data e ora che gia rileva di per sè.

    Vi posto i codici, perfavore datemi una mano sto davvero molto indietro con giava
    GRAZIE INFINITE!!!

    P.S. La classe Operatore è stata creata poichè il programma è ancora monothread, quando lo farò evolvere in multithread creerò una lista di operatori. SCUSATE X LE IMPERFEZIONI E GLI ERRORI. E' MOLTO CHE NON PROGRAMMO

    P.P.S Suddivido il Codice in varie risposte a questo Thread, perchè è molto lungo

  2. #2

    LATO CLIENT

    --- lato client ---

    codice:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    import java.awt.*;
    import java.awt.event.*;
    
    import javax.security.auth.login.LoginContext;
    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;
    
    /**
     *
     * @author Operatore
     */
    public class Cronometro extends javax.swing.JFrame {
        
        private Timer timer;
        private long startTime;
        
        String rigaTesto;
    
        BufferedReader in ;
        DataOutputStream  out;
        Socket clientSocket;
    
        /**
         * Creates new form CronometroClient
         */
        public Cronometro() {
            
            /**** COSTRUISCO GUI ****/
            initComponents();
            
            /***** COSTRUISCO TIMER ****/
            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);
     
                }
            });     
        }//FINE COSTRUTTORE
    
        /**
         * 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() {
    
            pannelloCronometro = new javax.swing.JPanel();
            labelTime = new javax.swing.JLabel();
            labelUserName = new javax.swing.JLabel();
            labelPassword = new javax.swing.JLabel();
            labelTelefono = new javax.swing.JLabel();
            username = new javax.swing.JTextField(15);
            telefono = new javax.swing.JTextField();
            password = new javax.swing.JTextField(15);
            labelTitle = new javax.swing.JLabel();
            panelBottoni = new javax.swing.JPanel();
            buttonLogin = new javax.swing.JButton();
            buttonLogout = new javax.swing.JButton();
            buttonPausa = new javax.swing.JButton();
            buttonRiprendi = new javax.swing.JButton();
            pannelloStatus = new javax.swing.JPanel();
            status = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setPreferredSize(new java.awt.Dimension(500, 500));
    
            labelTime.setFont(new java.awt.Font("SansSerif", 1, 50)); // NOI18N
            labelTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            labelTime.setText("\"0:00:00.0\"");
    
            labelUserName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            labelUserName.setText("Nome Utente");
    
            labelPassword.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            labelPassword.setText("Password");
    
            labelTelefono.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            labelTelefono.setText("Telefono");
    
            javax.swing.GroupLayout pannelloLayout = new javax.swing.GroupLayout(pannelloCronometro);
            pannelloCronometro.setLayout(pannelloLayout);
            pannelloLayout.setHorizontalGroup(
                pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pannelloLayout.createSequentialGroup()
                    .addGap(115, 115, 115)
                    .addGroup(pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(labelPassword)
                        .addComponent(labelUserName)
                        .addComponent(labelTelefono))
                    .addGap(18, 18, 18)
                    .addGroup(pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(username, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                        .addComponent(password))
                    .addGap(0, 0, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pannelloLayout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelTime, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(47, 47, 47))
            );
            pannelloLayout.setVerticalGroup(
                pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pannelloLayout.createSequentialGroup()
                    .addContainerGap(27, Short.MAX_VALUE)
                    .addComponent(labelTime, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelUserName)
                        .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(9, 9, 9)
    //.....CONTINUA

  3. #3

    LATO CLIENT

    codice:
    .addGroup(pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelPassword)
                        .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(9, 9, 9)
                    .addGroup(pannelloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelTelefono)
                        .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(19, 19, 19))
            );
    
            labelTitle.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
            labelTitle.setForeground(new java.awt.Color(0, 0, 255));
            labelTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            labelTitle.setText("Ludeca Log-In Client");
    
            buttonLogin.setText("CONNETTI");
            buttonLogin.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonLoginActionPerformed(evt);
                }
            });
    
            buttonLogout.setText("DISCONNETTI");
            buttonLogout.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonLogoutActionPerformed(evt);
                }
            });
    
            buttonPausa.setText("PAUSA");
            buttonPausa.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonPausaActionPerformed(evt);
                }
            });
    
            buttonRiprendi.setText("RIPRENDI");
            buttonRiprendi.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonRiprendiActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(panelBottoni);
            panelBottoni.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(buttonLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(buttonLogout, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(buttonPausa, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(buttonRiprendi, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(8, 8, 8))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buttonLogin)
                        .addComponent(buttonLogout)
                        .addComponent(buttonPausa)
                        .addComponent(buttonRiprendi))
                    .addGap(32, 32, 32))
            );
    
            status.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
            status.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            status.setText("Status Connesione");
    
            javax.swing.GroupLayout pannelloStatusLayout = new javax.swing.GroupLayout(pannelloStatus);
            pannelloStatus.setLayout(pannelloStatusLayout);
            pannelloStatusLayout.setHorizontalGroup(
                pannelloStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(status, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            pannelloStatusLayout.setVerticalGroup(
                pannelloStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pannelloStatusLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            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(labelTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(pannelloStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(panelBottoni, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(pannelloCronometro, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addContainerGap())))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelTitle)
                    .addGap(18, 18, 18)
                    .addComponent(pannelloCronometro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(pannelloStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(9, 9, 9)
                    .addComponent(panelBottoni, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void buttonLoginActionPerformed(java.awt.event.ActionEvent evt) {
           /***************** 1 CONNESSIONE AL SERVER *******/
            try { 
                clientSocket = new Socket("192.168.42.176",9911);
                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.toString()));
                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);       
    		buttonPausa.setEnabled(true);
    		status.setText("<html>Operatore Connesso in 
    Data e Ora:
    "+ data+"</html>");
    		// }	 
                }
                else if (confermaLogin.equals("DATI_ERRATI"))
                {
                    status.setText("ERRORE!!! Dati di Log-In Errata!!");
                }   
             } 
            catch (UnknownHostException err) 
    	 {
    		System.err.println("Errore: probelmi di comunicazione");
    	} 
            catch (IOException err1)
            {
                     System.err.println("Errore: probelmi di comunicazione");
            }
        }
    
        private void buttonLogoutActionPerformed(java.awt.event.ActionEvent evt) {
             timer.stop();
             buttonPausa.setEnabled(false);
             buttonLogin.setEnabled (false);
             buttonLogout.setEnabled (true);
             buttonRiprendi.setEnabled (true);                    
             Tempo tempoPausa = new Tempo();
             final Date dataPausa = tempoPausa.dataCompleta;
             status.setText("<html>Operatore Disconnesso
    Data e Ora:
    "+ dataPausa+"</html>");
             
             try
             {
            	 in.close();
            	 out.close(); 
             clientSocket.close();
             }
             catch (UnknownHostException err) 
    	 {
    		System.err.println("Errore: probelmi di comunicazione");
    	} 
            catch (IOException err1)
            {
                     System.err.println("Errore: probelmi di comunicazione");
            }
            
        }
    
        private void buttonPausaActionPerformed(java.awt.event.ActionEvent evt) {
                        timer.stop();
                        buttonPausa.setEnabled(false);
                        buttonLogin.setEnabled (false);
                        buttonLogout.setEnabled (true);
                        buttonRiprendi.setEnabled (true);                    
                        Tempo tempoPausa = new Tempo();
                        final Date dataPausa = tempoPausa.dataCompleta;
                		status.setText("<html>Operatore in Pausa
    Data e Ora:
    "+ dataPausa+"</html>");
        }
    
        private void buttonRiprendiActionPerformed(java.awt.event.ActionEvent evt) {
                        timer.restart();
                        buttonRiprendi.setEnabled (true);
                        buttonPausa.setEnabled(false);
                        buttonLogin.setEnabled(false);
        	            buttonLogout.setEnabled(true);       
        	            buttonPausa.setEnabled(true);
        	            Tempo tempoRipresa = new Tempo();
                        final Date dataRipresa = tempoRipresa.dataCompleta;
                	    status.setText("<html>Operatore in Pausa
    Data e Ora:
    "+ dataRipresa+"</html>");
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tu...feel/plaf.html 
             */

  4. #4

    FINE LATO CLIENT

    codice:
    try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Cronometro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Cronometro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Cronometro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Cronometro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Cronometro().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton buttonLogin;
        private javax.swing.JButton buttonLogout;
        private javax.swing.JButton buttonPausa;
        private javax.swing.JButton buttonRiprendi;
        private javax.swing.JLabel labelUserName;
        private javax.swing.JLabel labelPassword;
        private javax.swing.JLabel labelTelefono;
        private javax.swing.JPanel panelBottoni;
        private javax.swing.JLabel labelTime;
        private javax.swing.JLabel labelTitle;
        private javax.swing.JPanel pannelloCronometro;
        private javax.swing.JPanel pannelloStatus;
        private javax.swing.JTextField password;
        private javax.swing.JLabel status;
        private javax.swing.JTextField telefono;
        private javax.swing.JTextField username;
        String nome = new String("lello");
        
        // End of variables declaration
    }
    codice:
    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
    --- lato server ---

    codice:
    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;	
    	}
    
    	
    }

  5. #5

    LATO SERVER

    codice:
    import java.io.BufferedReader;
    
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class CronometroServer extends javax.swing.JFrame {
        
       static BufferedReader in ;
        static DataOutputStream  out;
    
        static ServerSocket serverSocket = null;
        static Socket clientSocket = null;
    
    
        /**
         * Creates new form CronometroServer
         */
        public CronometroServer() {
            initComponents();
        }
    
        /**
         	ATTENZIONE!! 
         	NON MODIFICARE ASSOLUTAMENTE IL CODICE DEL METODO void initComponent() !!!
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            buttonAggiorna = new javax.swing.JButton();
            buttonSalvaFile = new javax.swing.JButton();
            buttonCreaLogIn = new javax.swing.JButton();
            jScrollPane2 = new javax.swing.JScrollPane();
            schermoLog = new javax.swing.JTextArea();
            jScrollPane1 = new javax.swing.JScrollPane();
            schermoOperatori = new javax.swing.JTextArea();
            labelOperatori = new javax.swing.JLabel();
            labelLog = new javax.swing.JLabel();
            labelTitolo = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Ludeca Log-In Server");
    
            buttonAggiorna.setText("AGGIORNA");
    
            buttonSalvaFile.setText("SALVA FILE");
    
            buttonCreaLogIn.setText("CREA LOG-IN");
    
            schermoLog.setColumns(20);
            schermoLog.setRows(5);
            jScrollPane2.setViewportView(schermoLog);
            schermoLog.setEditable(false);
    
            schermoOperatori.setColumns(20);
            schermoOperatori.setRows(5);
            jScrollPane1.setViewportView(schermoOperatori);
            schermoOperatori.setEditable(false);
    
            labelOperatori.setFont(new java.awt.Font("SansSerif", 1, 14)); // NOI18N
            labelOperatori.setForeground(new java.awt.Color(0, 0, 255));
            labelOperatori.setText("Operatori Loggati");
    
            labelLog.setFont(new java.awt.Font("SansSerif", 1, 14)); // NOI18N
            labelLog.setForeground(new java.awt.Color(0, 0, 255));
            labelLog.setText("Storico");
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(buttonAggiorna, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(36, 36, 36)
                            .addComponent(buttonSalvaFile, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(35, 35, 35)
                            .addComponent(buttonCreaLogIn, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(26, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(labelOperatori)
                    .addGap(267, 267, 267))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelLog)
                    .addGap(309, 309, 309))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(labelOperatori)
                    .addGap(1, 1, 1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelLog)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buttonAggiorna)
                        .addComponent(buttonSalvaFile)
                        .addComponent(buttonCreaLogIn))
                    .addContainerGap())
            );
    
            labelTitolo.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            labelTitolo.setForeground(new java.awt.Color(0, 0, 255));
            labelTitolo.setText("Ludeca Log-In Server");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelTitolo)
                    .addGap(184, 184, 184))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(labelTitolo)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tu...feel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(CronometroServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(CronometroServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(CronometroServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(CronometroServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new CronometroServer().setVisible(true);
                }
            });
            
            try {
        		serverSocket = new ServerSocket(9911);
        	    System.out.println("Server: Sono attivo sulla Rete ");
        	    clientSocket = serverSocket.accept(); 
        	    //serverSocket.setReuseAddress(true);
        	     in= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        	    //Stream di output
        	     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");
        	    }
        	    
        	    schermoOperatori.setText("Operatore----> "+operatore.getIdentificatoreLogin().toString());
                clientSocket.close();
        	    in.close();
        	    out.close();             
        	 } 
        	    catch (IOException e) 
        	 {
        	     System.out.println(e);
        	     System.out.println("NON HO ACCETTATO LA CONNESSIONE");
        	  }
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton buttonAggiorna;
        private javax.swing.JButton buttonCreaLogIn;
        private javax.swing.JButton buttonSalvaFile;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JLabel labelLog;
        private javax.swing.JLabel labelOperatori;
        private javax.swing.JLabel labelTitolo;
        private static javax.swing.JTextArea schermoLog;
        private static javax.swing.JTextArea schermoOperatori;
        // End of variables declaration                   
    }

  6. #6
    Utente di HTML.it
    Registrato dal
    Sep 2012
    Messaggi
    707
    Per capire a che livello di dettaglio risponderti bisognerebbe che spiegassi di cosa si sta parlando.

    È un programma tuo, una specie di esperimento? Un tuo esercizio per ripassare java?
    Te lo chiedo perché non mi sembra una cosa tanto fatta bene, sembra una cosa improvvisata.
    Non c'è un protocollo sottostante, tutte le informazioni passano in chiaro, ...

    Se è solo un esperimento allora ti posso dare una risposta alla leggera, se fosse una cosa seria (spero veramente di no)
    allora ti indicherei molti più errori.

  7. #7

    GRAZIE!!!

    Il codice è sporco perchè ci sto lavorando da nemmeno una settimana. GUI realizzata con netbeans e tutto il resto con eclipse o file di testo. ecco il perchè del disordine totale che ovviamente aggiusterò... avresti dovuto vedere 2 o 3 giorni fa.
    settimana prossima riordinerò tutto in modo piu modulare con dei metodi, onde evitare di sporcare troppo il main. volevo provvedere quando implementerò il multithread, e mi farebbe piacere la tua perizia, davvero tanto.
    ti spiego, è un semplice cronometro che deve misurare al max le ore di lavoro e di pausa di alcune ragazze che devono fare delle interviste telefoniche in un centralino.
    il mio responsabile non mi ha chiesto niente di professionale, quantomeno una cosa sbrigativa. eccoti spiegato il perchè e ti ringrazio dell'interessamento a riguardo, dopo tutti quei copia e incolla non ho pensato di specificarlo prima io. :-)

    puoi darmi un consiglio a riguardo? nell'ottica che la settimana prossima, dopo che avrò ripulito il codice, dovrei rendere tutto multhitread? quindi non operare alcuna cosa che possa intralciare il multithread in futuro? potremmi tenerci in contatto anche x altri canali?

    grazie infinite!!

  8. #8
    Utente di HTML.it
    Registrato dal
    Sep 2012
    Messaggi
    707

    Re: GRAZIE!!!

    Originariamente inviato da lello82nap
    ti spiego, è un semplice cronometro che deve misurare al max le ore di lavoro e di pausa di alcune ragazze che devono fare delle interviste telefoniche in un centralino.
    il mio responsabile non mi ha chiesto niente di professionale, quantomeno una cosa sbrigativa.
    Allora io ti direi due cose:
    1) io al 100% avrei fatto quello che devi fare con una paginetta php (o jsp, o asp se conosci meglio). Il server http è ovviamente già multi-thread e lavori in contesto client-server (browser e server http) e con delle tecnologie (html, javascript, ...) che sono la morte loro per fare queste cose. Un programmatore php/asp/jsp ci mette al massimo 1 - 2 giorni a fare 2 paginette (login.php, index.php) che ti fanno fare il login e ti presentano gli stessi pulsanti per registrare il tempo (magari su un db).

    2) se proprio proprio proprio non hai altra scelta che farlo in java (dovrebbero proprio essere ragioni imprescindibili) ti consiglierei innanzitutto di pensare prima a una specie di protocollo, il più semplice possibile e di demandare il più possibile al server.
    Devi cercare di ridurre al minimo le informazioni che il client invia al server. Il client dovrebbe mandare solo 2 tipi messaggi: PAUSE e RESUME. Il tempo lo deve tenere il server, non deve essere inviato dal client al server. I client si devono fidare che il tempo che segna il server è giusto e ovviamente se vuoi visualizzare il tempo sul monitor dei client basta che tutte le macchine sia sicronizzate con un server ntp.

  9. #9

    GRAZIE MILLE!!!

    Hai perfettamente ragione sul punto 2, ed anche sul punto 1, solo che per quest'ultimo!!
    come un emerito idiota non avevo pensato alla soluzione piu' ovvia, includere la classe Tempo nel lato Client!
    Grazie mille fratello, se ti aggiorno qui ti viene notificato? anche se lo dovessi fare fra qualche giorno?

  10. #10
    p.s. la domanda sulle 3 variabili stringhe però resta.
    come posso fare x inviare 3 Stringhe scisse ma sempre relative al Singolo Operatore, senza utilizzare una stringa concatenata? E ovviamente senza confondere la pass di un utente con quella di un altro? ti spiego, io dovrei ricevere questi input dal Client sul Server

    - Nome
    - Pass
    - Codice Tel

    tale che

    if( Nome_dal_Client=Nome_sul_Server && Pass_dal_Client=Pass_sul_Server)
    {
    out.write "OK fai scattare cronometro alle ragazze"
    SchermoTextField.setText "Operatore = Nome è alla postazione 1123 in data Data_Log_In"
    }

    come posso fare?

    Credi che se alleggerisco il codice sarà difficile fraqualche giorno trasformare il server in multithread?
    GRAZIE!!!!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.