Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa
Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa
Marvel's Wolverine porta Logan in un'avventura inedita, violenta e fortemente narrativa, costruita attorno alla sua natura di combattente e al difficile rapporto con il proprio passato. Insomniac Games punta su combattimenti spettacolari, progressione e personalizzazione, inserendo l'azione in un mondo segnato dalla persecuzione dei mutanti. Un viaggio intenso, che alterna mattanza, esplorazione e momenti sorprendentemente emotivi.
DJI Romo 2: tante novità lo rendono un robot completo
DJI Romo 2: tante novità lo rendono un robot completo
Romo 2 è la seconda generazione di robot lavapavimenti di DJI, un modello che si caratterizza per la precisione nel sistema di navigazione e per il funzionamento particolarmente silenzioso. Con le modifiche introdotte in questa seconda versione, e un posizionamento di prezzo più allineato alla concorrenza, rappresenta una valida alternativa sul mercato delle soluzioni di pulizia domestica
Sony Bravia 9 II: il True RGB alla prova, dove l'LCD sfida l'OLED
Sony Bravia 9 II: il True RGB alla prova, dove l'LCD sfida l'OLED
Il primo Sony con retroilluminazione True RGB alla prova del banco di misura e dei contenuti: luminanza enorme, colori accurati in HDR e un antiriflesso molto efficace. I limiti sono due sole HDMI 2.1 e il blooming fuori asse
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


Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa Marvel's Wolverine, la recensione: Logan torna p...
DJI Romo 2: tante novità lo rendono un robot completo DJI Romo 2: tante novità lo rendono un ro...
Sony Bravia 9 II: il True RGB alla prova, dove l'LCD sfida l'OLED Sony Bravia 9 II: il True RGB alla prova, dove l...
Geely EX5, un mese al volante: il SUV elettrico cinese che ci ha sorpreso (quasi) senza riserve Geely EX5, un mese al volante: il SUV elettrico ...
Mova Z70 Ultra Roller Complete: motore potente, rullo di lavaggio e l'IA a guidare Mova Z70 Ultra Roller Complete: motore potente, ...
Avio si prepara ai test del Dimostratore...
Space Pioneer ha annunciato le cause del...
Anthropic avrebbe nuovi antibiotici cont...
Scoperto un 'moltiplicatore nascosto' ne...
DREO: a IFA 2026 4 novità fra cui...
Slackbot genera dashboard e microsite de...
Idrogeno, nuova cella a combustibile rag...
Con la NASA fuori dai giochi, l'ESA risc...
Una falla di ChatGPT permette di estrapo...
Piano clima, 1,34 miliardi per il bonus ...
Porsche esce definitvamente da Bugatti R...
NVIDIA App aggiunge una delle funzioni p...
Come sarebbe il mondo se la luce viaggia...
Titanio, ceramica e zaffiro per HUAWEI W...
Taglio delle accise sul gasolio prorogat...
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: 01:25.


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