Torna indietro   Hardware Upgrade Forum > Software > Programmazione

DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort
DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort
Fino a 740 km WLTP con la batteria da 97,2 kWh, sospensioni che leggono la strada con una telecamera e un abitacolo da salotto parigino. La nuova DS N°7 raccoglie l'eredità della DS 7 e la porta, per la prima volta, nel mondo 100% elettrico. Ecco come è fatta, cosa offre e quanto costa.
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più
Abbiamo provato Samsung Galaxy Tab S12 Ultra nella versione 12 GB + 256 GB con tastiera, e il risultato è un tablet che in questa configurazione si comporta come un notebook con la fluidità tipica di Android. Spessore di 5,1 mm, display Dynamic AMOLED 2X da 14,6 pollici, MediaTek Dimensity 9500 e un software senza incertezze compongono un prodotto di vertice, con prezzi da 1.539 euro, frenato solo da un'autonomia nella parte bassa del confronto
Hyundai IONIQ 5 N, l'elettrica che finge di essere termica (e ci riesce da paura)
Hyundai IONIQ 5 N, l'elettrica che finge di essere termica (e ci riesce da paura)
Abbiamo provato per dieci giorni la Hyundai IONIQ 5 N, con 650 CV, 770 Nm e uno 0-100 km/h in 3,4 secondi. Il suo punto forte è N e-Shift, che simula un cambio a otto rapporti con suoni da motore termico e perfino un bang supersonico
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 19-05-2004, 14:24   #1
anna182
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...) se l'ibutton in questione ha l'accesso alla porta il server inviera true al client altrimenti false. se il clien riceve true abilita i bottoni nel form altrimenti li lascia disabilitati... il problema e che una volta scollegato il bottone il client dovrebbe disabilitare ancora i bottoni e attendere che un nuovo ibutton si connetta invece questo non accade, una volta collegato un ibutton gli altri non vengono piu letti...qlc puo aiutarmi??'

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!!!
anna182 è offline   Rispondi citando il messaggio o parte di esso
Old 19-05-2004, 23:52   #2
pholcus
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
pholcus è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort DS N°7 E-Tense: il SUV premium made in Melfi...
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più Recensione Samsung Galaxy Tab S12 Ultra: non chi...
Hyundai IONIQ 5 N, l'elettrica che finge di essere termica (e ci riesce da paura) Hyundai IONIQ 5 N, l'elettrica che finge di esse...
CES Unveiled Milan, l'IA diventa tecnologia fondativa e il commercio torna centrale CES Unveiled Milan, l'IA diventa tecnologia fond...
 Recensione OPPO Find X10 Pro Max: un top di gamma completo con tre fotocamere da 200MP Recensione OPPO Find X10 Pro Max: un top di gam...
Mini PC Ryzen 5 con 32 GB di RAM e SSD d...
Le e-bike di Urlife spopolano su Amazon:...
Dashcam 70mai 4K da 69,99€, minimo stori...
I 5 robot per le pulizie più scon...
Apple annuncia i nuovi MacBook Pro con s...
Warhorse Studios colpita da un grave att...
MX Master 4, arriva l'edizione speciale ...
Kali Linux 2026.3 porta la caccia alle r...
Oracle si affida a OpenAI: ChatGPT e Cod...
Kaspersky punta su IA e servizi gestiti ...
Già sfruttata la falla Brotli che...
Potrebbe essere stato scoperto un nuovo ...
Claude Code, il prompt per scovare telec...
Palit e GALAX smentiscono le voci sulla ...
Fujifilm annuncia la Instax Mini Evo 2, ...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 08:08.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v