provaintermedia/ 0040755 0001750 0001750 00000000000 07665711404 012437 5 ustar lor lor provaintermedia/Articolo.java 0100644 0001750 0001750 00000001023 07662207636 015053 0 ustar lor lor package provaintermedia; import java.io.Serializable; public class Articolo implements Serializable { private int codice; private String descrizione; public Articolo(int codice, String descrizione) { this.codice = codice; this.descrizione = descrizione; } int getCodice() { return codice; } String getDescrizione() { return descrizione; } void setCodice(int codice) { this.codice = codice; } public String toString() { return "Articolo " + codice + ": " + descrizione; } } provaintermedia/AstaClient.java 0100644 0001750 0001750 00000005167 07662207636 015343 0 ustar lor lor package provaintermedia; import javax.swing.*; import java.awt.*; import java.net.*; import java.io.*; /** *
Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class AstaClient { private ClientManager cm; public AstaClient(int port) { try { cm = new ClientManager("127.0.0.1", port, this); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void start() { String nome = JOptionPane.showInputDialog("Inserisci il nome"); cm.login(nome); Object[] options = {"Mando un messaggio per vendere", "Aspetto" }; int scelta = JOptionPane.showOptionDialog(null,"Cosa vuoi fare?","Scegli",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[1]); if (scelta==0) { Articolo nuovo = new Articolo(123,"Enciclopedia Treccani"); cm.sendMessage(Messaggio.messaggioArticolo(nuovo,(float) 10000)); } while (true) { } } public void manageMessage(Messaggio m) { if (m!=null) { System.out.println(m); } else { return; } if (m.getCodice()==Messaggio.OFFERTA) { System.out.println("Viene offerto questo articolo:"); Articolo offerto = (Articolo) m.getMessaggio(); System.out.println(offerto.getDescrizione()); System.out.println("Al prezzo di " + m.getPrezzo()); Object[] options = { "faccio un'offerta", "Rifiuto" }; int scelta = JOptionPane.showOptionDialog(null, offerto.getDescrizione() + " per " + m.getPrezzo() , "Scegli", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (scelta == 0) { float prezzo = Float.parseFloat(JOptionPane.showInputDialog("Quanto offri?")); cm.sendMessage(Messaggio.messaggioOfferta(offerto,prezzo)); } else { cm.sendMessage(Messaggio.messaggioRifiuto()); } } } //Main method public static void main(String[] args) { if (args.length != 1) { System.err.println( "Devi specificare una porta come paramentro"); System.exit(1); } try { int port = Integer.parseInt(args[0]); new AstaClient(port).start(); } catch (NumberFormatException e) { System.err.println( "Devi specificare una porta come paramentro"); System.exit(1); } } } provaintermedia/AstaServer.java 0100644 0001750 0001750 00000033547 07662210550 015363 0 ustar lor lor package provaintermedia; import java.io.*; import java.net.*; import java.util.*; /** *Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class AstaServer { private ServerSocket sSock; /**tabella hash che contiene associati agli identificativi dei clienti * i loro OutputClient per mandare i messaggi
*/ private Hashtable clients = new Hashtable(); /**tabella hash che contiene associato ad ogni articolo * il suo banditore
*/ private Hashtable aste = new Hashtable(); /**tabella hash che contiene l'articolo per il quale un * cliente stato interrogato
*/ private Hashtable clientiinterrogati = new Hashtable(); /**serve per assegnare un codice univoco ad ogni articolo */
private int codicecorrente = 0;
/**
* Crea una nuova istanza di AstaServer
.
*
* @param sock ServerSocket
*/
public AstaServer(ServerSocket sock) {
sSock = sock;
}
/**
*
Costruisce il server
* @param port la porta dove girare * @exception IOException se si ha un errore nel creare il socket */ public AstaServer(int port) throws IOException { System.out.println("Viene creato il server"); sSock = new ServerSocket(port); } /** *Fa partire il server e lo mette in attesa di connessioni * che richiedono il login
*/ public void start() { while (true) { try { Socket cSock = sSock.accept(); new Thread(new StartConnection(cSock, this)).start(); } catch (IOException e) { System.err.println("Impossibile accettare la connessione"); } } } /** * @return true se l'utente connesso, false altrimenti */ private boolean connected(IdUtente utente) { return (clients.containsKey(utente)); } /** *Effettua il login di un utente
* @param utente l'utente di cui si vuole fare il login * @param outp l'OutputClient corrispondente al cliente * @return true se il login ha avuto successo */ public boolean login(IdUtente utente, OutputClient outp) { synchronized (clients) { if (connected(utente)) { System.out.println("L'utente " + utente + " esiste gi!"); return false; // in realt questo non dovrebbe mai succedere dato che possono esistere // pi utenti con lo stesso nome purch siano diversi l'host o la port } // inserisce il gestore dell'output nella tabella dei clienti clients.put(utente, outp); System.out.println("\n\nSi connette " + utente.toString()); return true; } } /** * Esegue il logout di un utente * * @param utenteIdUtente
*/
public void logout(IdUtente utente) {
System.out.println("Si disconnette " + utente.toString());
synchronized (clients) {
OutputClient oC = (OutputClient) clients.get(utente);
oC.stop();
clients.remove(utente);
Banditore b = (Banditore) clientiinterrogati.get(utente);
if (b != null) {
b.rifiuto(utente);
clientiinterrogati.remove(utente);
}
}
}
/**
* Invia un messaggio all'utente indicato.
* @param to IdUtente
destinatario
* @param msg il Messaggio
da inviare
* @return true se l'utente esiste. false altrimenti
*/
public boolean sendMessage(IdUtente to, Messaggio msg) {
System.out.println("Mando a " + to + " il seguente messaggio:\n" + msg);
synchronized (clients) {
OutputClient oC = (OutputClient) clients.get(to);
if (oC == null) {
return false; // se l'utente si disconnesso
}
oC.add(msg);
return true;
}
}
/**
* Metodo chiamato dalla classe InputClient per gestire messaggi di tipo
* ARTICOLO, RIALZO e RIFIUTO
* @param utente IdUtente
(mittente)
* @param m Messaggio
il messaggio inviato
*/
public void manageMessage(IdUtente utente, Messaggio m) {
System.out.println("E' arrivato un messaggio di " + utente + ":\n" + m);
if (m.getCodice() == Messaggio.ARTICOLO) {
lanciaAsta(utente, m);
}
else {
msgAsta(utente, m);
}
}
/**
* Metodo chiamato per creare una nuova asta.
*
* @param venditore un valore IdUtente
contenente il venditore
* @param m un Messaggio
contenente l'articolo e il prezzo
*/
private void lanciaAsta(IdUtente venditore, Messaggio m) {
System.out.println("\nInizia l'asta");
System.out.println(venditore + " vende il seguente articolo:");
Articolo daVendere = (Articolo) m.getMessaggio();
daVendere.setCodice(++codicecorrente); // assegna un codice univoco
System.out.println(daVendere.getCodice() + " " + daVendere.getDescrizione());
System.out.println("Prezzo iniziale: " + m.getPrezzo());
HashSet compratori;
synchronized (clients) {
compratori = new HashSet(clients.keySet());
// crea l'insieme dei possibili compratori.
// inzialmente contiene tutti i client
}
compratori.remove(venditore); // escluso il venditore
Banditore nuovobanditore = new Banditore(venditore, compratori, daVendere,
m.getPrezzo(), this);
synchronized (aste) {
aste.put(daVendere, nuovobanditore);
// inserisce il banditore nella tabella delle aste in esecuzione
}
new Thread(nuovobanditore).start(); // parte il Thread dell'asta
}
/**
* Metodo richiamato per gestire messaggi
* di tipo RIALZO o RIFIUTO
* @param id un IdUtente
mittente
* @param m il Messaggio
*/
private void msgAsta(IdUtente id, Messaggio m) {
Banditore b = (Banditore) clientiinterrogati.get(id);
// b il banditore dell'asta per cui l'utente stato interrogato
synchronized (clientiinterrogati) {
clientiinterrogati.remove(id);
}
System.out.println("E' arrivato un messaggio d'asta dall'utente " + id +
" lo levo da quelli da aspettare");
if (m.getCodice() == Messaggio.RIALZO) {
b.rialzo(id, m.getPrezzo());
}
else { // RIFIUTO
b.rifiuto(id);
}
synchronized (id) {
id.notify();
}
// risveglia le aste che stavano aspettando per interrogare questo utente
}
/**
* Metodo chiamato dal banditore per notificare la fine di un'asta
* @param a l' Articolo
al quale l'asta si riferisce
*/
public void fineAsta(Articolo a) {
System.out.println("E' finita l'asta per l'articolo " + a.getDescrizione() +
" (" + a.getCodice() + ")");
synchronized (aste) {
aste.remove(a); // toglie il banditore dalla tabella delle aste
}
}
/**
* Metodo richiamato dalla classe Banditore per inviare un messaggio
* di offerta a un cliente. Inserisce il cliente nella tabella dei
* clienti interrogati
*
* @param to l'IdUtente
destinatario
* @param b il Banditore
che richiama il metodo
* @param prezzo (float
) il prezzo d'offerta
* @return true se il messaggio stato inviato correttamente
* cio se il cliente ancora collegato
*/
public boolean inviaMessaggioOfferta(IdUtente to, Banditore b, float prezzo) {
synchronized (clientiinterrogati) {
System.out.println("Inserisco " + to +
" nella tabella dei clienti che devono rispondere");
clientiinterrogati.put(to, b);
boolean inviato = sendMessage(to,
Messaggio.messaggioOfferta(b.getArticolo(),
prezzo));
if (!inviato) {
clientiinterrogati.remove(to);
}
return inviato;
}
}
/**
* Per determinare se un utente stato interrogato per un'offerta
* ma non ha ancora risposto
*
* @param utente un IdUtente
* @return true se non ha risposto, false se non ha offerte pendenti
*/
public boolean impegnato(IdUtente utente) {
synchronized (clientiinterrogati) {
return (clientiinterrogati.containsKey(utente));
}
}
/**
* Metodo main, fa partire il sever
*
* @param args Prende un solo argomento, la porta dove mettersi in ascolto
* @exception IOException se non riesce a creare il socket
*/
public static void main(String[] args) throws IOException {
if (args.length != 1) {
throw new IllegalArgumentException("Sintassi: AstaServer Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class ClientManager { private Socket clientSocket; private ObjectOutputStream oos; public ClientManager(String host, int port,AstaClient client) throws IOException,UnknownHostException { clientSocket = new Socket(host,port); oos = new ObjectOutputStream(clientSocket.getOutputStream()); new Thread( new Waiter(client) ).start(); } public void sendMessage(Messaggio m) { try { oos.writeObject(m); } catch (IOException e) { e.printStackTrace(); } } public void login(String name) { sendMessage(Messaggio.messaggioLogin(name)); } class Waiter implements Runnable { private AstaClient client; private boolean run = true; public Waiter(AstaClient cl) { client = cl; } public void run() { while (run) { try { ObjectInputStream ois = new ObjectInputStream(clientSocket. getInputStream()); Object m = ois.readObject(); if (m instanceof Messaggio) client.manageMessage( (Messaggio) m); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } public void stop() { run = false; } } } provaintermedia/FrameClient.java 0100644 0001750 0001750 00000002002 07662207636 015466 0 ustar lor lor package provaintermedia; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** *Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class FrameClient extends JFrame { JPanel contentPane; BorderLayout borderLayout1 = new BorderLayout(); //Construct the frame public FrameClient() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } //Component initialization private void jbInit() throws Exception { contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(borderLayout1); this.setSize(new Dimension(400, 300)); this.setTitle("Client per l'asta"); } //Overridden so we can exit when window is closed protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } } provaintermedia/InputClient.java 0100644 0001750 0001750 00000003171 07662207636 015543 0 ustar lor lor package provaintermedia; import java.io.*; /** *Title: InputClient
*Description: Classe Runnable per un thread che ascolta un utente dell'asta
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class InputClient implements Runnable { private IdUtente utente; private ObjectInputStream ois; private AstaServer server; private boolean attivo = true; /** * Crea un nuovoInputClient
*
* @param utente IdUtente
l'utente da ascoltare
* @param ois l'ObjectInputStream
associato al socket del cliente
* @param server l'AstaServer
a cui riferirsi
*/
public InputClient(IdUtente utente, ObjectInputStream ois, AstaServer server) {
this.utente = utente;
this.ois = ois;
this.server = server;
}
/**
* Metodo implementato da Runnable che mette il thread in ascolto per
* nuovi messaggi
*
*/
public void run() {
while (attivo) {
try {
Object m = ois.readObject();
if (m instanceof Messaggio) {
server.manageMessage( utente, (Messaggio) m);
}
}
catch (EOFException e) {
attivo = false;
server.logout(utente);
}
catch (IOException e) {
e.printStackTrace();
attivo = false;
}
catch (ClassNotFoundException e) {
e.printStackTrace();
attivo = false;
}
}
}
/**
* Per fermare il thread costruito a partire da questa classe
*
*/
public void stop() {
attivo = false;
}
}
provaintermedia/Messaggio.java 0100644 0001750 0001750 00000004223 07662207636 015222 0 ustar lor lor package provaintermedia;
import java.io.Serializable;
public class Messaggio
implements Serializable {
public static int LOGIN = 0;
public static int ARTICOLO = 1;
public static int OFFERTA = 2;
public static int RIFIUTO = 3;
public static int RIALZO = 4;
public static int FINEOK = 5;
public static int DESERTA = 6;
public static int AGGIUDICATO = 7;
private static String[] codici = {
"LOGIN", "ARTICOLO", "OFFERTA", "RIFIUTO",
"RIALZO", "FINEOK", "DESERTA", "AGGIUDICATO"};
private int codice;
private Serializable messaggio;
private float prezzo;
public Messaggio(int codice, Serializable messaggio, float prezzo) {
this.codice = codice;
this.messaggio = messaggio;
this.prezzo = prezzo;
}
public static Messaggio messaggioLogin(String nome) {
return new Messaggio(LOGIN, nome, -1);
}
public static Messaggio messaggioArticolo(Articolo articolo, float prezzoBase) {
return new Messaggio(ARTICOLO, articolo, prezzoBase);
}
public static Messaggio messaggioOfferta(Articolo articolo,
float prezzoAttuale) {
return new Messaggio(OFFERTA, articolo, prezzoAttuale);
}
public static Messaggio messaggioRifiuto() {
return new Messaggio(RIFIUTO, null, -1);
}
public static Messaggio messaggioRialzo(float prezzo) {
return new Messaggio(RIALZO, null, prezzo);
}
public static Messaggio messaggioFineOK(Articolo articolo, float prezzo) {
return new Messaggio(FINEOK, articolo, prezzo);
}
public static Messaggio messaggioDeserta(Articolo articolo, float prezzo) {
return new Messaggio(DESERTA, articolo, prezzo);
}
public static Messaggio messaggioAggiudicato(Articolo articolo, float prezzo) {
return new Messaggio(AGGIUDICATO, articolo, prezzo);
}
public int getCodice() {
return codice;
}
public Serializable getMessaggio() {
return messaggio;
}
public float getPrezzo() {
return prezzo;
}
public String toString() {
return "Messaggio di " + codici[codice] + ": " + messaggio
+
( ( (codice != LOGIN) && (codice != RIFIUTO)) ? (" - prezzo: " + prezzo) :
"");
}
} provaintermedia/OutputClient.java 0100644 0001750 0001750 00000003326 07662210331 015730 0 ustar lor lor package provaintermedia;
import java.io.*;
import java.net.*;
import java.util.Vector;
/**
* Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author Lorenzo Masetti * @version 1.0 */ public class OutputClient implements Runnable { private ObjectOutputStream oos; private Vector messageQueue=new Vector(); private boolean attivo = true; /** * Crea unOutputClient
*
* @param o l'output stream relativo al client
* @exception IOException se non riesce a creare l'ObjectOutputStream
*/
public OutputClient(ObjectOutputStream o) throws IOException {
oos = o;
}
/**
* Aggiunge un nuovo messaggio alla coda di quelli da inviare
*
* @param msg il Messaggio
da aggiungere
*/
public void add(Messaggio msg) {
synchronized (messageQueue) {
messageQueue.add(msg);
messageQueue.notify();
}
}
/**
* Metodo implementato da Runnable. Mette il thread in attesa di
* messaggi da spedire e ogni volta che arriva un nuovo messaggio lo
* spedisce al cliente
*
*/
public void run() {
while (attivo) {
synchronized (messageQueue) {
try {
if (messageQueue.size() > 0) {
Object o = messageQueue.remove(0);
oos.writeObject(o);
}
else {
messageQueue.wait();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Per fermare il thread creato a partire da questa classe
*
*/
public void stop() {
attivo=false;
}
}
provaintermedia/Articolo.class 0100644 0001750 0001750 00000001500 07665711376 015243 0 ustar lor lor . /
! "
#
$
% &
' ( ) * codice I descrizione Ljava/lang/String;