Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [Java] Casino Client Server

    Premetto che questo è il mio primo programma in Java quindi ho parecchie lacune.

    Devo realizzare un sistema client server, dove il server può ricevere infinite connessioni e crea un thread per gestire ogni connessione.

    Il server è CollabServer, il Client è ServizioCinema e CollabHandler è la classe che si occupa di gestire una singola connessione.

    Ora ho numerosi problemi che principalmente sono:

    Invio e ricezione di oggetti (o meglio vettori di oggetti);
    Visibilità di variabili tra classi (non riesco a far vedere la stessa variabile a 2 classi differenti).

    Il server parte, accetta le connessioni, ma arrivato alle dichiarazioni degli object input stream si blocca e inzia a dare problemi.
    Stessa cosa per il client che si connette al server ma, una volta dichiarati gli object stream, cessa di funzionare.

    posto il codice delle 3 classi sopra citate mettendo in grassetto i punti in cui da problemi, spero che qualcuno di voi mi possa aiutare.

    CollabServer
    codice:
    package serverclientprova;
    
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    public class CollabServer {
    //--------------------------------------------------
    protected static FilmInProg [] vFiP; /*HO PROVATO A DICHIARARE 
    STATICA QUESTO VETTORE DI OGGETTI FilmInProg PER RENDERLA 
    VISIBILE A COLLABHANDLER MA NON FUNZIONA*/
    protected String info = "";
    protected BufferedReader bis;
    protected BufferedWriter bos;
    protected int nM;
    
    
        public CollabServer() throws IOException {
            MemorizzaFile();
            nM = ContaMatrici();
            vFiP = new FilmInProg [nM];
            CreaVettore();
            ServerSocket server = new ServerSocket(1414);
            
            System.out.println ("Accepting connections...");
            while(true) {
                Socket client = server.accept();  //ogni richiesta di connessione  viene accettata
                System.out.println ("Accepted from " + client.getInetAddress());
                try{
                new CollabHandler(client, info, nM);
                }catch(IOException e){
                    System.out.println("IO Exception" + "\n");   
               }//Istanziamo un oggetto CollabHandler per gestire la connessione        }
            }
       }
            
    
       public void MemorizzaFile () throws IOException {
           try{
               bis = new BufferedReader(new InputStreamReader(new FileInputStream("DbCinema.txt"))); //apriamo il file di testo contenente le info
               String temp = "";
               while( (temp = bis.readLine()) != null)
                info = info + temp + "\n";
               } catch(IOException e){
                    System.out.println("IO Exception" + "\n");   
               }
               finally {
                    try {
                        bis.close();
                    } catch (IOException e) {
                         System.out.println("IO Exception" + "\n");
                    }
               }
        }
        
        
        public int ContaMatrici () throws IOException { //conta il numero delle matrici che dovranno esser create
          String inputLine = "";
          int num = 0;
          try { 
              bis = new BufferedReader(new InputStreamReader(new FileInputStream("DbCinema.txt"))); //apriamo il file di testo contenente le info
              inputLine = bis.readLine();
              while (inputLine.compareTo("FINE") != 0) {              
                    bis.readLine();
                    inputLine = bis.readLine();
                    while (inputLine.compareTo("---") != 0) {
                        num++;
                        inputLine = bis.readLine();
                    }
                    inputLine = bis.readLine();
                }
          }
            catch (IOException e) {
            System.out.println("IO Exception" + "\n");
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                     System.out.println("IO Exception" + "\n");
                    }
                }
            return num;
         }
       
       public void CreaVettore () throws IOException {
           String NomeF, NomeS, t;
           int i = 0;   
           try{
                bis = new BufferedReader(new InputStreamReader(new FileInputStream("DbCinema.txt")));
                NomeF = bis.readLine();
                while (NomeF.compareTo("FINE") != 0){
                        NomeS = bis.readLine();
                        t = bis.readLine();
                        while (t.compareTo("---") != 0){ 
                             vFiP[i] = new FilmInProg( NomeF, NomeS, t);
                             i++;
                             t = bis.readLine();
                        }
                     //per me questa cosa va gestita meglio... che facciamo continuiamo il while ugualemte????
                    NomeF = bis.readLine();
                    }
                }catch (IOException e) {
                    System.out.println("IO Exception" + "\n");
                }finally{
                    try {
                        bis.close();
                    } catch (IOException e) {
                         System.out.println("IO Exception" + "\n");
                    }    
                }
         }
        
    //--------------------------------------------------
        public static void main(String args[]) throws IOException {
            new CollabServer();
        
        }
    }

  2. #2
    ServizioCinema
    codice:
    package clientserverprova;
    
    
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    //import prominence.msg.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class ServizioCinema extends Frame {
        protected static int id = 0;
        Label LMsgServer, LInfoFilm, LSala, LOrario, LPostiLiberi;
        TextArea TAInfoFilm, TAMsgServer;
        TextField TFSala, TFOrario, TFPostiLiberi;
        Button BRichiedi, BPostiLiberi, BCompra, BReset;
        MessageOutputStream Mos;
        MessageInputStream Mis;
        ObjectInputStream Ois; 
        ObjectOutputStream Oos;
        Button [][] Mb; 
        String S, O;
        short [][] D;
        Color g, r, b;    
    
        
        public ServizioCinema (InputStream i, OutputStream o)  throws IOException {
            super ("Servizio Cinema " + (id ++));
            this.setLayout(null); //che fa????
            setResizable(false);
            try {
                Mos = new MessageOutputStream (o);
                Mis = new MessageInputStream (i);
                Ois = new ObjectInputStream (i);
                Oos = new ObjectOutputStream (o); /* QUI SI BLOCCA TUTTO E MI FA CASINI, NON RIESCO A CAPIRE PERCHE' */
                
           }catch (IOException e){
                System.out.println("oh 4");
                System.out.println("IOException E" + "\n");
            }
           
                  
            
            
            g = Color.GREEN;
            r = Color.RED;
            b = Color.BLUE;
    
            
            //   setLayout (new GridLayout (2, 1)); che fa????
            resize(570, 700);//controllare
            
            int x = 50, y = 200;
            Mb = new Button [15][10];
            for (int z = 0; z < 15; z++){
                for (int c = 0; c < 10; c++){
                    Mb[z][c] = new Button (Integer.toString(z)+Integer.toString(c));
                    Mb[z][c].reshape(x, y, 25, 18);
                    Mb[z][c].hide();
                    this.add(Mb[z][c]);
                    x = x + 30;
                }
            y = y + 20;    
            x = 50;
            }
    
    
            LMsgServer = new Label("Messaggi dal server");
            LMsgServer.reshape(20, 520, 200, 15);
            this.add(LMsgServer);
            LInfoFilm = new Label("Info programmazione film sale e orari");
            LInfoFilm.reshape(20, 40, 250, 15);
            this.add(LInfoFilm);
            LSala = new Label("Sala");
            LSala.reshape(440, 175, 100, 15);
            this.add(LSala);
            LOrario = new Label("Orario");
            LOrario.reshape(440, 230, 100, 15);
            this.add(LOrario);
            LPostiLiberi = new Label("Posti Liberi");
            LPostiLiberi.reshape(440, 334, 100, 15);
            this.add(LPostiLiberi);
            
            TFSala = new TextField();
            TFSala.reshape(440, 200, 100, 20);
            this.add(TFSala);
            TFOrario = new TextField();
            TFOrario.reshape(440, 255, 100, 20);
            this.add(TFOrario);
            TFPostiLiberi = new TextField();
            TFPostiLiberi.reshape(440, 360, 100, 20);
            this.add(TFPostiLiberi);
            
            TAInfoFilm = new TextArea();
            TAInfoFilm.reshape(20, 60, 400, 100);
            this.add(TAInfoFilm);
            TAMsgServer = new TextArea();
            TAMsgServer.reshape(20, 550, 500, 120);
            this.add(TAMsgServer);
            
            BRichiedi = new Button("Info Film");
            BRichiedi.reshape(440, 70, 80, 50);
            this.add(BRichiedi);
            BPostiLiberi = new Button("Posti liberi");
            BPostiLiberi.reshape(440, 280, 80, 40);
            this.add(BPostiLiberi);
            BCompra = new Button("Compra");
            BCompra.reshape(440, 400, 80, 80);
            this.add(BCompra);
            BCompra.hide();
            BReset = new Button("Reset");
            BReset.reshape(370, 430, 50, 30);
            this.add(BReset);
            show(); ////////////////////////
       
    
                    //rinominiamo i bottoni della matrice con i e j e renderli invisibili
                    //il bottone compra nn è visibile, diventa visibile dopo aver schiacciato posti liberi
            }
        
        
        @Override
        public boolean handleEvent(Event event) {
            g = Color.GREEN;
            r = Color.RED;
            b = Color.BLUE;
            
            if (event.id == Event.WINDOW_DESTROY) {
            hide(); // hide the Frame
            dispose(); // tell windowing system to free resources
            System.exit(0); // exit
            return true;
            }
            if (event.target == BRichiedi && event.id == Event.ACTION_EVENT) {
                BRichiedi_Clicked(event);
            }
            else if (event.target == BPostiLiberi && event.id == Event.ACTION_EVENT) {
            BPostiLiberi_Clicked(event);
            }
            else if (event.target == BCompra && event.id == Event.ACTION_EVENT) {
                try {
                    BCompra_Clicked(event);
                } catch (IOException ex) {
                    Logger.getLogger(ServizioCinema.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ServizioCinema.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else if (event.target == BReset && event.id == Event.ACTION_EVENT) {
            BReset_Clicked(event);
            }
            else 
                for (int i = 0; i < 15; i++)
                    for (int j = 0; i < 15; i++)
                        if (event.target == Mb[i][j] && event.id == Event.ACTION_EVENT  
                        && Mb[i][j].getForeground() == g ) {
                            buttonM_Clicked(i, j, event);
            }
    
    return super.handleEvent(event);
    }
    //--------------------------------------------------
    void BRichiedi_Clicked(Event event) {
        try{
            Mos.writeUTF("Richiedi");
            Mos.send();
        }catch (IOException e){
            System.out.println("Errore nella richiesta delle informazioni" + "\n");
        }
        TAInfoFilm.setText(""); //per cancellare il testo
        try{
            Mis.receive();
            TAInfoFilm.append(Mis.readUTF() + "\n");
        }catch (IOException e){
            System.out.println("Errore nella richiesta delle informazioni" + "\n");
        }
    }
    //--------------------------------------------------
    void BPostiLiberi_Clicked(Event event) {
            try {
                short[][] temp;
                temp = new short[15][10];
                String s;
                int n;
    
                S = TFSala.getText();
                O = TFOrario.getText();
                //gestire try catch
                Mos.writeUTF("PostiLiberi");
                Mos.send();
                Mos.writeUTF(S);
                Mos.writeUTF(O);
                Mos.send();
                Mis.receive();
                n = Mis.readInt();
                if (n == -1) {
                    System.out.println("Attenzione!! Il nome della sala o l'orario è inesistente!");
                } else {
                    temp = (short[][]) Ois.readObject();        ///////// object
                    TFPostiLiberi.setText(Integer.toString(n));
                    for (int i = 0; i < 10; i++) {
                        for (int j = 0; j < 15; j++) {
                            if (temp[i][j] == 0) {
                                Mb[i][j].setForeground(g);
                                Mb[i][j].show();
                            } else if (temp[i][j] == 1) {
                                Mb[i][j].setForeground(r);
                            }
                            Mb[i][j].show();
                            /*   else if (temp[i][j] == 2)
                            Mb[i][j].hide(); nn serve perchè è già nascosto di default*/
                        }
                    }
                    BCompra.hide();
                }
            } catch (IOException ex) {
                Logger.getLogger(ServizioCinema.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ServizioCinema.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
    //--------------------------------------------------
    void BCompra_Clicked(Event event) throws IOException, ClassNotFoundException {
        try{
            Mos.writeUTF("Compra"); //invio il comando
            Mos.send();
            Mos.writeUTF(S);
            Mos.writeUTF(O);
            Mos.send();
        }catch (IOException e) {
            System.out.println("IO Exception" + "\n");
        }
        Oos.writeObject(D);/////////////////////OBJECT
        Mis.receive();
        int check = Mis.readInt();
        if (check == 1 )//fallimento posti già acquistati
            TAMsgServer.append(Mis.readUTF() + "\n");
        else{ //check == 0
            TFPostiLiberi.setText(Integer.toString(Mis.readInt()) + "\n");
            TAMsgServer.append(Mis.readUTF() + "\n");
            BReset_Clicked(event);
        }    
      }
    
    
    //--------------------------------------------------
    void BReset_Clicked(Event event) {
        b = Color.BLUE;
        g = Color.green;
        for (int i = 0; i < 15; i++)
            for (int j = 0; i < 15; i++)
                D[i][j] = 0;
        BCompra.hide();
        for (int i = 0; i < 10; i++)
                for (int j = 0; j < 15; j++){
                    if (Mb[i][j].getForeground() == b ){
                        Mb[i][j].setForeground(g);
                        Mb[i][j].show();
                    }
                }
    }
    
    //--------------------------------------------------
    void buttonM_Clicked(int l, int m, Event event) {
        b = Color.BLUE;
        Mb[l][m].setForeground(b);
        D[l][m] = 1;
        BCompra.show();
    }
    
    
        
        static public void main (String args[]) throws IOException {
            Socket socket = new Socket("localhost", 1414);
            new ServizioCinema (socket.getInputStream(),socket.getOutputStream()).show();
     
               
        }
    }

  3. #3
    CollabHandler:

    codice:
    package serverclientprova;
    
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    // import prominence.msg.*; ?????
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    
    
    public class CollabHandler extends Thread {
        protected Socket socket;
        protected MessageInputStream mis;
        protected MessageOutputStream mos;
        protected ObjectInputStream ois;
        protected ObjectOutputStream oos;
        protected int nM;
        protected String info;
        
        //--------------------------------------------------
        public CollabHandler(Socket socket, String info, int nM) throws IOException {
           this.socket = socket;
           this.info = info;
           this.nM = nM;
              try{
                mis = new MessageInputStream(socket.getInputStream());
                mos = new MessageOutputStream(socket.getOutputStream());
                }catch (IOException e) {
                    System.out.println("IO Exception" + "\n");
                 }
           try{
              
                ois = new ObjectInputStream(socket.getInputStream());
                 
                oos = new ObjectOutputStream(socket.getOutputStream());/* si blocca anche qui, impedendo così al thread di partire*/ 
    
           }catch (IOException e) {
                System.out.println("QuestaIO Exception" + "\n");
            }
           start();
        }
        
        
        
    
        @Override
        public void run ()   {
            
            try{
                while(true){
                    mis.receive();
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException ex) {}
                    String cmd = mis.readUTF(); //che metodo bisogna usare??
                    if (cmd.equals ("Richiedi"))
                        Richiedi(); //controlla mis mos anche se secondo me nn servono visto che mis e mos sono dichiarate fuori da ogni metodo e dal costruttore compreso
                    else if (cmd.equals ("PostiLiberi")){
                        mis.receive();
                        String Sala = mis.readUTF();
                        String Orario = mis.readUTF();
                        PostiLiberi(Sala, Orario);//idem 
                    }
                    else if (cmd.equals ("Compra"))
                        Compra();//idem
                }
            }
            catch (ClassNotFoundException ex) {
                Logger.getLogger(CollabHandler.class.getName()).log(Level.SEVERE, null, ex);
            }        catch (IOException ex){
            ex.printStackTrace();
            }
            //siamo sicuri???? no per niente infatti l'ho tolto perche' le nostre funzioni nn hanno eccezioni forse boh da rivedere
        } 
    
        public void Richiedi (){
            try {
                mos.writeChars(info);
                mos.send();
            }catch  (IOException e) {
                System.out.println("IO Exception" + "\n");
            }
            
        }
            
            
        public void PostiLiberi (String NomeS, String Ora) throws IOException, ClassNotFoundException {
            int ok = 0;
            int i = 0;
            /*String prova;
            prova = vFiP[0].NomeFilm;*/
            while(ok == 0 && i < nM ){
                if (vFiP[i].Sala.compareTo(NomeS) == 0 && vFiP[i].Orario.compareTo(Ora) == 0){ //cerca l'istanza di FilmInProg desiderata
                    try {
                        mos.writeInt(vFiP[i].PostiL);
                        mos.send();
                    }catch  (IOException e) {
                        System.out.println("IO Exception" + "\n");  
                        //return; io ci metterei un return
                    }
                    try {
                    oos.writeObject(vFiP[i]);
                    }
                    catch  (IOException e) {
                        System.out.println("IO Exception" + "\n");  
                        //return; io ci metterei un return
                    }
                    //ma send qui nn serve???
                    ok = 1;
                }
                else i++;
            }
            if(ok == 0){
                try {
                mos.writeInt(-1);//il client dovrà mandare a schermo un msg di errore
                mos.send(); //se non trova una matrice (quindi sala e/o orario sono errati) invio un numero di posti liberi negativo
                }catch  (IOException e) {
                        System.out.println("IO Exception" + "\n");
                }
        }
        }
        
        public void Compra () throws IOException, ClassNotFoundException {
            int ok = 0,  i = 0;
            short [][] p;
            p = new short [15][10];
            String Orario, Sala;
            try {      
                mis.receive();
                Sala = mis.readUTF();
                Orario = mis.readUTF();
            }
            catch (IOException e){
                System.out.println("IO Exception" + "\nErrore nella ricezione. Ripetere l'operazione Compra");
                return; //ma questo lo legge il server nn il client quindi è sbaglaito
            }   
            p = (short [][]) ois.readObject();     //fare try e catch   
            while(ok == 0){
                if ( vFiP[i].Sala.compareTo(Sala) == 0 && vFiP[i].Orario.compareTo(Orario) == 0) //cerca l'istanza di FilmInProg desiderata
                    ok = 1;
                else i++;
            }
            CompraS(i, p); //non serveche la definiamo qui la matrice p possiamo definirla direttamente in compraS visto che è
            //lì che viene utilizzata
        }
        
        
        public void CompraS (int k, short [][] s) throws IOException, ClassNotFoundException { 
            synchronized (vFiP[k]){
            int cont = 0, r = 0, c;
            while (r < 15){
                c = 0;
                while (c < 10) {
                    if (s[r][c] == 1) //se troviamo un uno nella matrice di acquisto
                        if (vFiP[k].P[r][c] == 0){  
                            vFiP[k].P[r][c] = 1;
                            cont++; //controllare inizializzazione a 0
                        }
                        else if (vFiP[k].P[r][c] == 1){
                            try{
                                mos.writeInt(1); //fallimento 
                                mos.writeUTF("Spiacente! Uno o più posti sono già stati acquistati! \n Prego selezionare altri posti");
                                mos.send();
                            }catch (IOException e){
                                System.out.println("IO Exception" + "\n");
                            }//finally???
                            PostiLiberi(vFiP[k].Sala, vFiP[k].Orario); //si potrebbe fare un altro metodo a cui gli passi direttamente ilò FilmInProg
                            return;
                        }
                    c++;
                }
                r++;
            }
       /*     if (cont == 0){ 
                try{
                    mos.writeInt(2);//errore!!
                    mos.writeUTF("Non sono stati selezionati posti, prego ripete l'operazione");
                    mos.send();
                }catch (IOException e){
                    System.out.println("IO Exception" + "\n");
                }
                return;
            }*/
            vFiP[k].PostiL = vFiP[k].PostiL - cont;
            try{
                mos.writeInt(0);//tutto ok
                mos.writeInt(vFiP[k].PostiL); //spedisce il num dei restanti posti liberi
                mos.writeUTF("I posti sono stati acquistati correttamente!");
                mos.send();
            }catch (IOException e){
                System.out.println("IO Exception" + "\n");
            }
            }
        }
    }

    Spero proprio nel vostro aiuto, sono disperato

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.