Torna indietro   Hardware Upgrade Forum > Software > Programmazione

HONOR CHOICE Projector Air Pro: piccolo, portatile e con Netflix
HONOR CHOICE Projector Air Pro: piccolo, portatile e con Netflix
Un proiettore economico, che fa della portabilità e immediatezza i suoi punti di forza. Adatto per una camera da letto o per la casa vacanze, è basato su sistema proprietario Linux ma offre piena compatibilità ufficiale a Netflix
ASUS ProArt GoPro Edition è il notebook compatto per chi crea
ASUS ProArt GoPro Edition è il notebook compatto per chi crea
Un notebook sviluppato in collaborazione con GoPro ma che risponde al meglio alle necessità di tutti coloro che creano contenuti video: robustezza, design, potenza di calcolo e funzionalità si abbinano al meglio tra di loro, pur se a prezzo di un costo elevato per via della tanta memoria onboard
Fable e Sol a confronto: due cartoni animati creati su un PC con RTX 3090
Fable e Sol a confronto: due cartoni animati creati su un PC con RTX 3090
Ho affidato ai due modelli lo stesso mestiere ma non lo stesso identico prompt: trasformare una storia illustrata in un video usando una RTX 3090 e modelli locali. Ne sono usciti due film, due applicazioni e due idee opposte di efficienza. Fucina, progettata con Fable 5, colpisce di più nei primi secondi. Storyboard Studio, costruito con ChatGPT/Codex, regge meglio sulla distanza e vince il confronto complessivo, ma di stretta misura
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 19-05-2004, 13: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, 22: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


HONOR CHOICE Projector Air Pro: piccolo, portatile e con Netflix HONOR CHOICE Projector Air Pro: piccolo, portati...
ASUS ProArt GoPro Edition è il notebook compatto per chi crea ASUS ProArt GoPro Edition è il notebook c...
Fable e Sol a confronto: due cartoni animati creati su un PC con RTX 3090 Fable e Sol a confronto: due cartoni animati cre...
Il tablet rugged leggero e sottile: Lenovo ThinkTab X11 offre resistenza, doppia USB-C e batteria rimovibile Il tablet rugged leggero e sottile: Lenovo Think...
AMD Advancing AI 2026: l'hardware AMD per le elaborazioni IA del futuro, tra GPU, CPU e robot AMD Advancing AI 2026: l'hardware AMD per le ela...
OpenAI taglia i prezzi di due modelli GP...
RTX Spark pronto a dominare anche i tabl...
Il primo telefono davvero senza bordi no...
DeepSeek V4-Flash, API in beta pubblica:...
La crisi delle memorie continuerà: ecco ...
Dati su disfunzione erettile e perdita d...
Arriva e-invoice, il servizio di fiskaly...
Champions League, F1 e MotoGP: ecco la p...
Amazon alza a 220 miliardi le stime sugl...
World of Warcraft e Dungeons & Drago...
AXOL Server ridisegna l'infrastruttura d...
MSI ha ucciso AMD EXPO ULL? High-Efficie...
Falso Portale dell'Automobilista ruba pa...
Apple chiude il miglior trimestre di giu...
Sony tira dritto sull'addio ai dischi Pl...
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: 03:16.


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