|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Member
Iscritto dal: May 2004
Messaggi: 60
|
JAVA
sto creando un sistema client server con una comunicazione via socket. il client deve leggere un ibutton collegato alla seriale e inviarne il codice al server, il server tramite un file deve verificare l'accesso(per chi avesse letto il mio post di prima funziona ora...)
CLIENT: import com.dalsemi.onewire.OneWireAccessProvider; import com.dalsemi.onewire.adapter.DSPortAdapter; import com.dalsemi.onewire.container.OneWireContainer; import java.util.Enumeration; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.net.InetAddress.*; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.lang.*; import java.lang.String.*; import java.io.*; import java.util.StringTokenizer; /* * FormLeggi.java * * Created on 12. maggio 2004, 10:35 */ /** * * @author Anna Jaquinta */ public class FormLeggi extends javax.swing.JFrame{ //Variabili String host = "127.0.0.1"; int port = 2000; static Socket socket; OutputStream oStream; static InputStream iStream; static String servStr = ""; int i = 0; OneWireContainer owd; JLabel code; JTextField ID; static JButton bApriPorta; static JButton bStatoPorta; static String FileName; BufferedReader input = null; int posporta; int posutente; static String str; boolean accessoOk = false; String idlettore = "5B0000018A1B5409"; /** Creates new form FormLeggi */ public FormLeggi(){ code = new JLabel("IButton code: "); JPanel Ibutton = new JPanel(); JPanel codice = new JPanel(); JPanel bottoni = new JPanel(); ID = new JTextField(20); bApriPorta = new JButton("ApriPorta"); bStatoPorta = new JButton("Visualizza stato porta"); bottoni.setLayout(new GridLayout(2,2)); Ibutton.setLayout(new GridLayout(1,1)); codice.setLayout(new GridLayout(2,1)); bottoni.add(bApriPorta); bottoni.add(bStatoPorta); codice.add(code); Ibutton.add(ID); getContentPane().add(bottoni, BorderLayout.SOUTH); getContentPane().add(codice, BorderLayout.WEST); getContentPane().add(Ibutton, BorderLayout.CENTER); GestisciBottone ApriPorta = new GestisciBottone(); GestisciBottone2 VisualizzaStato = new GestisciBottone2(); bApriPorta.addActionListener(ApriPorta); bStatoPorta.addActionListener(VisualizzaStato); bApriPorta.setEnabled(false); bStatoPorta.setEnabled(false); pack(); this.setSize(500,500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); try{ //creazione socket socket = new Socket(host, port); } catch(Exception e){ System.out.println(e); } initComponents(); } //creo metodo che scrive un testo nel TEXTFIELD public void ScriviTesto(String iButtonCode){ ID.setText(iButtonCode); } //invia stringa a server public void sendToSocket(Socket socket, String str)throws IOException{ System.out.println("Stringa inviata: " + str); oStream = socket.getOutputStream(); for (i=0; i<str.length();i++){ oStream.write(str.charAt(i)); } oStream.write('\n'); } //legge stringa da server public static String readFromSocket(Socket socket)throws IOException { iStream = socket.getInputStream(); String str =""; char c; while(((c=(char)iStream.read())!= '\n')){ str = str + c; } return str; } /** 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. */ private void initComponents() { addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); pack(); } /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0); } //verifica risposta dal server public static void accesso(){ try{ //legge risposta dal server ("true" o "false") servStr = readFromSocket(socket); System.out.println("Accesso: " + servStr); if(servStr.equals("true")){ //attiva bottoni nel frame se risp è true bApriPorta.setEnabled(true); bStatoPorta.setEnabled(true); } if(servStr.equals("Utente disconnesso")){ //disattiva bottoni nel frame se utente toglie bottone bApriPorta.setEnabled(false); bStatoPorta.setEnabled(false); } } catch(Exception e){ e.printStackTrace(); } } //ascoltatore bottone porta public class GestisciBottone implements ActionListener{ public void actionPerformed(ActionEvent E) { RichiediApertura(); } } //ascoltatore bottone stato porta public class GestisciBottone2 implements ActionListener { public void actionPerformed(ActionEvent E) { RichiediStato(); } } //richiede aprtura della porta al server public void RichiediApertura(){ try{ //socket = new Socket(host, port); sendToSocket(socket, "Apri"); servStr = readFromSocket(socket); //repaint(); System.out.println("Risposta del Server: " + servStr); } catch(Exception e){ System.out.println(e); } } //richiede lo stato della porta al server public void RichiediStato(){ try{ //socket = new Socket(host, port); sendToSocket(socket, "Stato"); servStr = readFromSocket(socket); System.out.println("Risposta del Server: " + servStr); } catch(Exception e){ e.printStackTrace(); } } /** * @param args the command line arguments */ //main public static void main(String args[]) { //creo costruttore formleggi FormLeggi f = new FormLeggi(); f.show(); String oldId = ""; String currentId = ""; DSPortAdapter adapter = null; Lettore LettoreReader = null; String idlettore = "5B0000018A1B5409"; try { // get the default adapter adapter = OneWireAccessProvider.getDefaultAdapter(); //costruttore lettore LettoreReader = new Lettore(adapter); // get exclusive use of adapter adapter.beginExclusive(true); // clear any previous search restrictions adapter.setSearchAllDevices(); adapter.targetAllFamilies(); adapter.setSpeed(adapter.SPEED_REGULAR); } catch (Exception e1) { System.out.println("errore riscontrato: " + e1); try { // end exclusive use of adapter adapter.endExclusive(); // free port used by adapter adapter.freePort(); } catch(Exception e2) { System.out.println("errore riscontrato: " + e2); } } while(true){ try{ currentId = Lettore.leggi("5B0000018A1B5409"); //richiamo il metodo scrivi testo. f.ScriviTesto(currentId); } catch(Exception e){ System.out.println("Errore: " + e); } if(!currentId.equals(oldId)){ oldId = currentId; try{ f.sendToSocket(socket, currentId); f.accesso(); } catch(Exception e){ System.out.println("Errore: " + e); } } if(!oldId.equals("")){ while(true){ //System.out.println("OLDID" + oldId); f.accesso(); } } } } } // Variables declaration - do not modify // End of variables declaration //classe lottore, utilizzata per leggere il codice dell'ibutton class Lettore{ static DSPortAdapter adapter = null; Lettore(){ } Lettore(DSPortAdapter ad){ adapter = ad; } public static String leggi(String IDLettore)throws Exception { OneWireContainer owd; String currentId = ""; // carica indirizzi try{ for (Enumeration owd_enum = adapter.getAllDeviceContainers();owd_enum.hasMoreElements() owd = (OneWireContainer) owd_enum.nextElement(); currentId = owd.getAddressAsString(); // se IDlettore e diverso da idcorrente ritorna id corrente al cervello if(!IDLettore.equals(currentId)){ return currentId; } } return ""; //nel caso in cui non ha trovato bottone } catch(Exception e){ throw e; } } } FINE CLIENT SERVER: import java.net.*; import java.lang.*; import java.io.*; import java.util.StringTokenizer; import java.io.BufferedReader.*; import java.net.InetAddress.*; import java.net.ServerSocket.*; import java.io.InputStream.*; class ProvaServer{ private String FileName; String s=""; BufferedReader input = null; int posporta; int posutente; boolean accessoOK = false; static InputStream iStream; static OutputStream oStream; static int i = 0; static ServerSocket welcomeSocket; static Socket socket; static String str = ""; public static void main(String []args){ while(true){ try{ welcomeSocket = new ServerSocket(2000); socket = welcomeSocket.accept(); System.out.println("ho ricevuto la richiesta di connessione"); InetAddress ip = socket.getInetAddress(); System.out.println("Indirizzo Ip del client che richiede la connessione: " + ip.toString()); while(true){ rispondi(socket); } } catch(IOException e){ System.out.println(e); } } } public static void sendToSocket(Socket socket, String str)throws IOException{ oStream = socket.getOutputStream(); for (i=0; i<str.length();i++){ oStream.write(str.charAt(i)); } oStream.write('\n'); } public static String readFromSocket(Socket socket)throws IOException{ iStream = socket.getInputStream(); String str=""; char c; while(((c=(char)iStream.read())!= '\n')){ str = str + c; } System.out.println("Stringa ricevuta: " + str); if(str.equals("0E0000008F33A802")){ //System.out.println("Verifica"); String IDUtente = "0E0000008F33A802"; String IDPorta = "5B0000018A1B5409"; verificaAccessi(IDUtente, IDPorta); } if(str.equals("0B00000034D4D602")){ String IDUtente = "0B00000034D4D602"; String IDPorta = "5B0000018A1B5409"; verificaAccessi(IDUtente, IDPorta); } if(str.equals("5B0000018A1B5409")){ str = "Utente disconnesso"; sendToSocket(socket, str); } if(str.equals("Stato")){ System.out.println("Ho ricevuto la richiesta di visualizzazione dello stato della porta"); } if(str.equals("Apri")){ System.out.println("Ho ricevuto la richiesta di apertura della porta"); } return str; //InetAddress ip = socket.getInetAddress(); //System.out.println("Indirizzo Ip del client " + ip.toString()); } public static void rispondi(Socket socket)throws IOException{ str = readFromSocket(socket); if(str.equals("Apri")){ sendToSocket(socket, "Server: apro la porta"); } if(str.equals("Stato")){ sendToSocket(socket, "Server: visualizzo lo Stato"); } } public String getAccessFile(){ return(FileName); } public static void setAccessFile(String FileName){ FileName = "accesso.txt"; } public static boolean verificaAccessi(String IDUtente, String IDPorta){ int mask; int accesso; int posporta; int posutente; String token="-1000"; boolean accessoOK = false; int posaccesso = 0; String s=""; BufferedReader input = null; try{ input = new BufferedReader(new FileReader("accesso.txt")); } catch(FileNotFoundException E1) { E1.printStackTrace(); } try{ s = input.readLine(); } catch(Exception E2) { E2.printStackTrace(); } posporta = Fposizione(IDPorta,s); try{ s = input.readLine(); } catch(Exception E2) { E2.printStackTrace(); } posutente = Fposizione(IDUtente,s); try{ s = input.readLine(); } catch(Exception E2) { E2.printStackTrace(); } //System.out.println("prova s1: "+s); StringTokenizer st = new StringTokenizer(s); //System.out.println("prova s2: "+s); int i=0; while (st.hasMoreTokens() && i <= posutente) { token = st.nextToken(";"); i++; } int accCode = Integer.parseInt(token); /*System.out.println("Token: " + token); System.out.println("Codice accesso: " + accCode); System.out.println("Pos utente " + posutente); System.out.println("Pos porta " + posporta);*/ accessoOK = (accCode & (0x1 << posporta)) != 0; //System.out.println("accesso OK prima " + accessoOK); InvioAccesso(accessoOK); //System.out.println("accessoOK dopo " + accessoOK); return accessoOK; } public static void InvioAccesso(boolean accessoOK){ //System.out.println("accesso OK ricevuto " + accessoOK); if(accessoOK == true){ str = "true"; try{ sendToSocket(socket, str); System.out.println("Invio true al socket"); } catch(IOException e){ System.out.println(e); } } if(accessoOK == false){ str = "false"; try{ sendToSocket(socket, str); System.out.println("Invio false al socket"); } catch(IOException e){ System.out.println(e); } } } public static int Fposizione(String IDButton, String s){ int i = 0; StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { String token = st.nextToken(";"); if(token.equals(IDButton)){ return i; } else{ i++; } } return -1; } } FINE SERVER Accesso.txt 5B0000018A1B5409; 0E0000008F33A802;0B00000034D4D602; 0;255;
__________________
anna182 vivi come se dovessi morire domani, pensa come se non dovessi morire mai!!!
|
|
|
|
|
|
#2 |
|
Member
Iscritto dal: Oct 2002
Messaggi: 293
|
Ti rispondo di fretta perche' nn ho avuto tempo di leggere tutto il codice..domani magari
Cmnq.. potresti con una catch al posto giusto puoi capire quando avviene la disconnessione e nella catch scrivi il codice per disabilitare i bottoni.. Ciao |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 19:05.



















