Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Peugeot Polygon Concept: ecco il futuro delle utilitarie
Peugeot Polygon Concept: ecco il futuro delle utilitarie
Polygon è la concept car di Peugeot che mostra il futuro delle soluzioni del segmento B: tra design compatti e innovativi affiancati da dimensioni compatte uno scherzo dalla manovrabilità incredibile per le manovre a bassa velocità
Reno16 Pro: il compatto di OPPO punta su fotocamera da 200MP e il nuovo Bubble! La recensione
Reno16 Pro: il compatto di OPPO punta su fotocamera da 200MP e il nuovo Bubble! La recensione
OPPO ha portato in Italia, dal 1° luglio 2026, Reno16 Pro: display AMOLED da 6,32 pollici a 144Hz, tripla fotocamera con sensore principale da 200 megapixel, chip Dimensity 8550 Super e batteria da 6000mAh, al prezzo di lancio di 899 euro. Lo abbiamo provato per due settimane insieme al nuovo accessorio Bubble, per capire se la formula compatta della serie regge ancora di fronte a un listino da 1099 euro
 Hisense 55U7SE: tuttofare e accessibile, il MiniLED per film, sport e gioco
Hisense 55U7SE: tuttofare e accessibile, il MiniLED per film, sport e gioco
MiniLED di fascia media con local dimming a 192 zone, 144 Hz nativi e audio firmato Devialet. La prova strumentale riscontra colori affidabili e gaming reattivo, per un prodotto molto accessibile e convincente. Ma la soundbar aggiuntiva è quasi d'obbligo
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


Peugeot Polygon Concept: ecco il futuro delle utilitarie Peugeot Polygon Concept: ecco il futuro delle ut...
Reno16 Pro: il compatto di OPPO punta su fotocamera da 200MP e il nuovo Bubble! La recensione Reno16 Pro: il compatto di OPPO punta su fotocam...
 Hisense 55U7SE: tuttofare e accessibile, il MiniLED per film, sport e gioco Hisense 55U7SE: tuttofare e accessibile, il Min...
Kindle Scribe Colorsoft: riduce le cornici e diventa a colori, ma il prezzo è alto Kindle Scribe Colorsoft: riduce le cornici e div...
L'IA cambia tutte le regole della sicurezza tra vulnerabilità e sorveglianza. Intervista al CEO di Proofpoint L'IA cambia tutte le regole della sicurezza tra ...
Redmi Note 17 a un passo dal debutto, ma...
Gli aumenti di prezzo del PS Plus potreb...
Almeno 64 GB di RAM per giocare? Il caso...
Gemini si integrerà con le auto e potrà ...
Addio a OxygenOS di OnePlus e alla Realm...
Intel conferma l'aumento dei prezzi su C...
In vendita Withings BodyFit, molto più d...
Inkterface: Steam Machine ospita un pann...
Stare seduti oltre 30 minuti di fila aum...
A Milano l'Italia ha firmato la sovranit...
Cos'è PeerTube, la piattaforma di...
In 12 articoli TOP c'è il meglio ...
La pirateria è l'unica tutela per...
Roomba Plus 516 Combo in offerta a 479€:...
ASUS ROG Strix G16 con RTX 5070 Ti super...
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: 19:05.


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