Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 11

Discussione: problemi con chat

  1. #1
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107

    problemi con chat

    salve a tutti sto sviluppando una chat in java con possibilità di scambio messaggi oltre che pubblici anche privati.

    La chat funziona come segue:

    c'è una finestra in cui il partecipante alla chat si collega inserendo il proprio nome utente, dopodichè tale nome viene inserito in una lista di tutti gli utenti connessi in chat pubblica.

    Nel momento in cui un utente volesse iniziare una chat privata con un altro utente, basta che clicchi sul relativo nome all'interno della lsita degli utenti connessi e si aprono altre 2 finestre per poter per mettere ai 2 utenti la comunicazione tra di loro.

    Lato client ho i seguenti metodi :

    codice:
    package chatApplet;
    
    import java.net.*;
    import java.io.*;
    
    /**
     * Classe che implementa l'invio e la ricezione dei messaggi Client
     *
     * 
     */
    
    public class ClientChat
    {
       private DataOutputStream os;
       private BufferedReader is;
       private DataOutputStream os_PVT;
       private BufferedReader is_PVT;
       private Socket socket;
       private Socket sockPVT;
    
       /**
        * Metodo per la connessione client al server
        * @throws UnknownHostException
        * @throws IOException
        * @throws ConnectException
        */
    
       public void start() throws UnknownHostException,IOException,ConnectException
       {
    
         try{
                Socket sock=new Socket();
                sock.connect(new InetSocketAddress("127.0.0.1",7777));
    
                //Stream di byte da passare al Socket
                os = new DataOutputStream(sock.getOutputStream());
                is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            }
         catch(Exception e){
    
         }
       }
    
       public void startPVT() throws UnknownHostException,IOException,ConnectException
       {
    
         try{
               Socket SockPVT=new Socket();
               SockPVT.connect(new InetSocketAddress("127.0.0.1",7777));
    
              //Stream di byte da passare al Socket
              os_PVT = new DataOutputStream(SockPVT.getOutputStream());
              is_PVT = new BufferedReader(new InputStreamReader(SockPVT.getInputStream()));
    
            }
         catch(Exception e){
    
         }
       }
    
       /**
        * Metodo per l'invio del messaggio
        *
        * @param strMessage Testo contenente il messaggio
        * @throws IOException
        * @throws NullPointerException
        */
    
       public void inviaMessaggio(String strMessage) throws IOException,
               NullPointerException
       {
            try{
                os.writeBytes(strMessage + '\n');
            }
            catch(Exception e){
    
            }
       }
    
       public void inviaPVT(String strPVT) throws IOException, NullPointerException
       {
            try
            {
               os_PVT.writeBytes(strPVT + '\n');
            }
            catch(Exception pvt)
            {
    
            }
       }
    
       /**
        * Metodo per la ricezione del messaggio
        * @return restituisce il messaggio appena ricevuto
        * @throws IOException
        */
    
        public String MessaggiRicevuti() throws IOException
       {
          try
          {
             return is.readLine();
         }
          catch(NullPointerException e)
          {
              return "";
          }
        }
    
        /**
         *
         * @return
         * @throws IOException
         */
        public String MessaggiPVTRicevuti() throws IOException
        {
            return is_PVT.readLine();
        }
    
       /**
        * Metodo che chiude tutti i flussi stream e la Socket
        * @throws IOException
        * @throws NullPointerException
        */
    
       public void close() throws IOException,NullPointerException
       {
          System.out.println("Chiusura client");
          os.close();
          System.out.println("Chiusura stream os");
          is.close();
          System.out.println("Chiusura stream is");
          socket.close();
          System.out.println("Chiusura socket");
       }
    
       public void closePVT() throws IOException,NullPointerException
       {
          System.out.println("Chiusura client privato");
          os_PVT.close();
          System.out.println("Chiusura stream ospvt");
          is_PVT.close();
          System.out.println("Chiusura stream ispvt");
          try
          {
              sockPVT.close();
              System.out.println("Chiusura socket");
           }
          catch(NullPointerException ex)
          {
              System.out.println("");
          }
       }
    }

  2. #2
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    lato server
    codice:
    package chatServer;
    import java.net.*;
    import java.io.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    /*
     * La connessione client viene stabilita quando un utente si connette
     * alla chat.
     * Il simbolo ~ all'inizio del nickname di un utente indica che è nuovo
     * Il simbolo ^ all'inizio del nickname di un utente,indicare che deve essere
     * eliminato
     */
    
    public class ServerChat
    {
    
       private ServerSocket serverSocket;
       int clientPort;
       ArrayList clients;
       ArrayList nicks;
       ArrayList pvtUsers;
    
        @SuppressWarnings({"unchecked", "unchecked"})
       public void start() throws IOException
       {
          clients = new ArrayList();
          nicks = new ArrayList();
          pvtUsers=new ArrayList(1);
          Socket client;
          serverSocket = new ServerSocket(7777);
          getServerInfo();
    
             try
             {
                while (true)
                {
                     client = ascoltoClient();
                     clients.add(client);
                     getClientInfo(client);
                     SingleClientThread(client);
                }
             }
             catch (Exception ex)
             {
                 serverSocket.close();//chiudo il server
             }
        }
    
       /**
       * Metodo che crea un thread per ogni client connesso
        * @param client socket di connessione con il client
        * @throws InterruptedException
       */
    
      /*
       * t, variabile di tipo Thread
       * su ogni thread si chiama il metodo che crea dei buffer per la
       * comunicazione con il client
       *
       */
    
       public void SingleClientThread(Socket client) throws InterruptedException
    
       {
          Thread t = new Thread (new BufferServer(client));
          t.start();
       }
    
       /**
       * Classe che associa ad ogni client un buffer per la lettura delle richieste
       * del client e per l'invio delle risposte
       *
       */
    
       public class BufferServer implements Runnable
       {
          Socket client;
          BufferedReader is;
          DataOutputStream os;
    
          /**
           *
           * @param client
           */
    
    
          public BufferServer(Socket client)
          {
             this.client = client;
             try
             {
                // Stream di byte utilizzato per la comunicazione via socket
                is = new BufferedReader(new InputStreamReader(client.getInputStream()));
                os = new DataOutputStream(client.getOutputStream());
             }
             catch (Exception ex)
             {
             }
          }
    
          /**
           * Metodo della classe runnable per restare in ascolto dei messaggi in arrivo.
           */
    
          public void run()
          {
             try
             {
                while (true)
                {
                   // invio i messaggi
                   inviaMessaggio(MessaggiRicevuti(is), is, os, client);
                }
             }
             catch (Exception ex)
             {
             }
          }
       }
    
       /**
       * Metodo che processa le informazioni sul Server in ascolto
       */
    
       public void getServerInfo()
       {
    
          InetAddress indirizzo = serverSocket.getInetAddress();
          String server = indirizzo.getHostAddress();
          int port = serverSocket.getLocalPort();
          System.out.println("Lato Server: " + server + " porta: " + port);
       }
       /**
      *  Metodo che stampa le Informazioni sul Client che ha effettuato la chiamata
      * @param client socket del client di cui si vogliono stampare le informazioni
      */
    
       public void getClientInfo(Socket client)
       {
          InetAddress address = client.getInetAddress();
          String clientInfo = address.getHostName();
          clientPort = serverSocket.getLocalPort();
          System.out.println("Lato Client: " + clientInfo + " porta: "+ clientPort);
       }
    
       /**
      * Metodo con cui il server rimane in attesa di connnessione client
      * @throws IOException
      * @return connessioni client accettate dal server
      */
       public Socket ascoltoClient() throws IOException
       {
          System.out.println("In attesa di un CLIENT... ");
          serverSocket.setSoTimeout(600000);//il server si chiude dopo 10 minuti di inattività
          return serverSocket.accept();
       }
       /**
       * Metodo che legge i messaggi inviati utilizzando il buffer di lettura
       * @param is buffer per la lettura dei messaggi
       * @throws IOException
       * @return una stringa con il messaggio appena ricevuto
       */
      /*
       * variabile: strReceived, attraverso il buffer is e il metodo readLine() legge il
       * messaggio
       */
    
        @SuppressWarnings({"unchecked", "unchecked"})
       public String MessaggiRicevuti(BufferedReader is) throws IOException
       {
          String strReceived = is.readLine();
    
          if(strReceived.startsWith("~"))
          {
             // Controlla se il nickname(con cui viene identificato ogni utente)è gia' presente
             if (nicks.contains(strReceived.substring(1)))
             {
                strReceived = "Nickname scorretto";
             }
             else
                nicks.add(strReceived.substring(1));
          }
          else if(strReceived.startsWith("^"))
          {
             nicks.remove(strReceived.substring(1));
          }
          else if(strReceived.startsWith("_"))
          {
             if(pvtUsers.isEmpty()){
    
                  pvtUsers.add(strReceived.substring(1));
             }
          }
    
          System.out.println("Il Client ha inviato: " + strReceived);
          return strReceived ;
       }
    
       /**
      * Metodo per l'invio dei messaggi,ogni messaggio inviato viene letto da tutti
      * gli altri connessi
      * @param recMsg stringa con il messaggio ricevuto
      * @param is
      * @param os
      * @param client
      * @throws IOException
      */
    
      public void inviaMessaggio(String recMsg, BufferedReader is,
              DataOutputStream os,Socket client ) throws IOException
      {
          int idxToRemove = -1;
          for(Iterator all = clients.iterator(); all.hasNext();)
          {
             Socket cl = (Socket)all.next();
             if(recMsg.startsWith("~")) //se l'utente ha il simbolo ~ iniziale
                aggNuovoUtente(recMsg, cl, client); //viene aggiunto
             else if(recMsg.startsWith("^")) //altrimenti eliminato dalla chat
                idxToRemove = rimuoviUtente(recMsg, idxToRemove, cl, client);
             else if(recMsg.startsWith("_")){
                utenteChatPvt(recMsg, cl, client);
             }
             else
             {
              if(recMsg.equals("Nickname scorretto") && cl.equals(client))
              {
                new DataOutputStream(cl.getOutputStream()).writeBytes(recMsg + "\n");
                idxToRemove = rimuoviUtente(recMsg, idxToRemove, cl, client);
              }
              else
                  smistaMessaggi(recMsg, cl);
                  smistaMessaggiPVT(recMsg,cl);
             }
          }
          /*
           * Se ci sono client da rimuovere, tale rimozione viene effettuata
           * solo al termine del ciclo per evitare problemi sugli indici.
          */
          if (idxToRemove > -1)
             clients.remove(idxToRemove);
       }
    
      /**
      * Metodo che aggiunge nuovi utenti alla chat e stampa a video l'avvenuta aggiunta
      * @param recMsg
      * @param cl
      * @param client
      * @throws IOException
      */
    
      public void aggNuovoUtente(String recMsg, Socket cl, Socket client)
              throws IOException
       {
          if (cl.equals(client))
          {
             StringBuilder response = new StringBuilder();
             for (int i = 0; i < nicks.size(); i++)
             {
                response.append(nicks.get(i));
                response.append("~");
             }
    
             String strResponse = "Nickname corretto " + response.toString();
             System.out.println(strResponse);
          new DataOutputStream(cl.getOutputStream()).writeBytes(strResponse + "\n");
          }
          else
          {
             String strName = recMsg.substring(1);
             new DataOutputStream(cl.getOutputStream()).writeBytes("Nuovo Utente"
                       +strName + "\n");
          }
       }
    
      /**
       *
       * @param recMsgPVT
       * @param clPVT
       * @param client
       * @throws IOException
       */
      public void utenteChatPvt(String recMsgPVT,Socket clPVT,Socket client)
            throws IOException
      {
          if (clPVT.equals(client)){
                StringBuilder string = new StringBuilder();
                string.append(pvtUsers);
                string.append("_");
                String strPvt="Utente Privato" + string.toString();
                System.out.println(strPvt);
                new DataOutputStream(clPVT.getOutputStream()).writeBytes(strPvt + "\n");
    
          }
          else{
             String strNamePVT = recMsgPVT.substring(1);
             new DataOutputStream(clPVT.getOutputStream()).writeBytes("Utente Privato" +strNamePVT + "\n");
          }
     }
       /**
         * Metodo per la rimozione di un utente dalla chat
         * @param recMsg
         * @param idxToRemove
         * @param cl
         * @param client
         * @throws IOException
         * @return idxToRemove
         */
    
        /*
         * Metodo per la rimozione di un utente dalla chat. Nel momento in cui un utente
         * abbandona la chat viene chiuso lo stream sul client e restituito a video un
         * messaggio che sta ad indicare la corretta rimozione dell'utente(e del
         * relativo indice)
         */
    
      public int rimuoviUtente(String recMsg, int idxToRemove, Socket cl,
              Socket client) throws IOException
       {
          if (cl.equals(client))
          {
             close(cl.getInputStream(), cl.getOutputStream(), cl);
             idxToRemove = clients.indexOf(cl);
          }
          else
          {
             String strName = recMsg.substring(1);
           new DataOutputStream(cl.getOutputStream()).writeBytes("Rimuovi Utente " +
                strName + "\n");
          }
          return idxToRemove;
       }
    
       /**
       * Metodo che smista i messaggi
       * @param recMsg
       * @param cl
       * @throws IOException
       */
    
      public void smistaMessaggi(String recMsg, Socket cl) throws IOException
       {
          /*
           * Il messaggio "Nickname scorretto" deve essere inviato
           * solo ad uno specifico  client (gestito nella inviaMessaggio).
          */
    
          if(! recMsg.equals("Nickname scorretto") )
             new DataOutputStream(cl.getOutputStream()).writeBytes(recMsg + "\n");
    
          try{
               DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
               java.util.Date date = new java.util.Date();
               //System.out.println("Current Date Time : " + dateFormat.parse(date));
               FileWriter fstream = new FileWriter("LOG.txt",true);
               BufferedWriter dout = new BufferedWriter(fstream);
               String Mex=recMsg;
               dout.write(date+"\n"+Mex+"\n");
               dout.close();
          }catch (FileNotFoundException ex) {}
          catch(IOException ex){}
    
      }
      public void smistaMessaggiPVT(String recMsgPVT, Socket clPVT) throws IOException
       {
          /*
           * Il messaggio "Nickname scorretto" deve essere inviato
           * solo ad uno specifico  client (gestito nella inviaMessaggio).
          */
    
          if( recMsgPVT.equals("Utente Privato") )
             new DataOutputStream(clPVT.getOutputStream()).writeBytes(recMsgPVT + "\n");
    
          try{
               DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
               java.util.Date date = new java.util.Date();
               //System.out.println("Current Date Time : " + dateFormat.parse(date));
               FileWriter fstream = new FileWriter("LOG_PVT.txt",true);
               BufferedWriter dout = new BufferedWriter(fstream);
               String Mex=recMsgPVT;
               dout.write(date+"\n"+Mex+"\n");
               dout.close();
          }catch (FileNotFoundException ex) {}
          catch(IOException ex){}
    
      }
       /**
     * Metodo che chiude la comunicazione di un certo client con il server
     * @param is
     * @param os
     * @param client
     * @throws IOException
     */
    
      public void close(InputStream is, OutputStream os, Socket client)
          throws IOException
       {
          System.out.println("Comunicazione client in chiusura");
          // chiusura della comunicazione con il Client
          os.close();
          is.close();
          System.out.println("Comunicazione con il client terminata: " +
             client.getInetAddress().getHostName() + " su porta: " + clientPort);
          client.close();
       }
    
      public static void main(String[] args)
       {
          ServerChat serverChat = new ServerChat();
          try
          {
             serverChat.start();
          }
          catch (Exception ex)
          {
             ex.printStackTrace();
          }}}

  3. #3
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    Questa è la chat privata

    codice:
    package chatApplet;
    
    import chatApplet.ClientChat.*;
    import java.awt.*;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.JLabel;
    
    public class PrivateChat extends JFrame {
    
        private static final long serialVersionUID=8L; //L sta per LONG
        private JLabel destinatario;
        private JLabel mittente;
        private List fontNameBox;
        private List fontStyleBox;
        private List fontSizeBox;
        private DefaultListModel listModel;
        private JButton buttonPvt;
        private JButton disconnetti;
        private JScrollPane jScrollPane1;
        private JScrollPane jScrollPane2;
        private JScrollPane jScrollPane3;
        public JTextArea viewmsg;//text area dove appare il messaggio inviato
        public JTextArea messaggio; //text area dove inserire il messaggio da inviare
        public Font font;
        private String resultName; //varivabile con il font cambiato
        private Integer resultSize; //variabile con la grandezza cambiata
        public String nickname;
        private JList lstUsers;
        private JPanel jPanel1;
        public ClientChat n_client;
        public chatApplet.Applet chat;
        public boolean isClientConnected;
    
    
       public PrivateChat() throws IOException
       {
            listModel = new DefaultListModel();
            lstUsers=new JList(listModel);
            jPanel1=new JPanel();
    
            viewmsg = new JTextArea();
            viewmsg.setColumns(20);
            viewmsg.setRows(5);
            viewmsg.setEnabled(false);
    
            messaggio=new JTextArea("");
        	messaggio.setEditable(true);
    
            jScrollPane1 = new JScrollPane();
            jScrollPane1.setViewportView(messaggio);
            jScrollPane2 = new JScrollPane();
            jScrollPane2.setViewportView(viewmsg);
            jScrollPane3=new JScrollPane();
            jScrollPane3.setViewportView(lstUsers);
    
            buttonPvt = new JButton();
            buttonPvt.setText("Send");
            buttonPvt.addActionListener(new ActionListener()
            {
                 public void actionPerformed(ActionEvent e)
                {
                    invio_actionPerformed(e);
                }
            });
    
            disconnetti= new JButton();
            disconnetti.setText("Go out");
            disconnetti.addActionListener(new ActionListener()
            {
                 public void actionPerformed(ActionEvent e)
                {
                    try {
                        disconnetti_actionPerformed(e);
                    } catch (IOException ex) {
                        Logger.getLogger(PrivateChat.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
    
            fontNameBox = new List();
            fontNameBox = new List(4);
    
            String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
            for ( int i = 0; i < fonts.length; i++)
                fontNameBox.add(fonts[i]);
            fontNameBox.select(0);
    
            fontSizeBox = new List();
            fontSizeBox = new List(4);
    
            for ( int i = 10; i < 40; i++)
                fontSizeBox.add(String.valueOf(i));
            fontSizeBox.select(0);
    
            fontStyleBox = new List();
            fontStyleBox = new List(4);
    
            fontStyleBox.add("Normal");
            fontStyleBox.add("Bold");
            fontStyleBox.add("Italic");
            fontStyleBox.select(0);
    
            ActionListener eventForwarder = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Font ft;
                    ft=FontChose();
                    messaggio.setFont(ft);
                }
              };
            fontNameBox.addActionListener(eventForwarder);
            fontSizeBox.addActionListener(eventForwarder);
            fontStyleBox.addActionListener(eventForwarder);
    
            destinatario = new JLabel();
            destinatario.setForeground(new java.awt.Color(255, 255, 255));
            destinatario.setText("Destinatario");
    
            mittente = new JLabel();
            mittente.setForeground(new java.awt.Color(255, 255, 255));
            mittente.setText("Mittente");
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(fontNameBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(6, 6, 6)
                    .addComponent(fontSizeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(6, 6, 6)
                    .addComponent(fontStyleBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(mittente)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(10, 10, 10)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(disconnetti, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(buttonPvt)))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(420, Short.MAX_VALUE)
                    .addComponent(destinatario)
                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(destinatario)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(fontNameBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(fontSizeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(fontStyleBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(8, 8, 8)
                    .addComponent(mittente)
                    .addGap(6, 6, 6)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(disconnetti)
                            .addGap(27, 27, 27)
                            .addComponent(buttonPvt)))
                    .addContainerGap(22, Short.MAX_VALUE))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    )
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
    
            pack();
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);
           jPanel1.setBackground(new Color(255, 153, 0));
           jPanel1.setFont(new Font("Serif", 0, 14));
           jPanel1.setForeground(new Color(51, 51, 255));
           this.setTitle("Chat Privata Chespettacolo");
           this.setLocation(200, 100);
           this.setVisible(true);
           this.setResizable(false);
       }
    
        PrivateChat(ClientChat client, String text, Applet app) {
            n_client=client;
            nickname=text;
            chat=app;
        }
    
         public Font FontChose(){
             Font ft;
             int style;
             resultName =fontNameBox.getSelectedItem();
             resultSize=(Integer.valueOf(fontSizeBox.getSelectedItem()));
             if(fontStyleBox.getSelectedItem().equals("Italic"))
                    style = Font.ITALIC;
                    else if(fontStyleBox.getSelectedItem().equals("Bold"))
                            style = Font.BOLD;
                    else style=Font.PLAIN;
             ft = new Font(resultName,style ,resultSize);
    
             return ft;
         }
    
         public Font getSelectFont(){
                 return font;
         }
        public void invio_actionPerformed(ActionEvent e)
        {
              // Se non e' stato inserito alcun messaggio, nulla da fare
          if (messaggio.equals(""))
          {
            JOptionPane.showMessageDialog(null, "Messaggio vuoto", "alert",
            JOptionPane.CANCEL_OPTION);
    
          }
    
          try
          {
    
            n_client.inviaPVT(this.nickname  + ": "
                                                 + (messaggio.getText()));
             messaggio.setText("");
          }
          catch (Exception ex)
          {
          }
        }
    
        /**
         *
         * @param e
         * @throws IOException
         */
    
        public void disconnetti_actionPerformed(ActionEvent e) throws IOException
        {
            int n =JOptionPane.showConfirmDialog(null," Vuoi abbandonare la chat? " ,
                "Chiusura chat privata",  JOptionPane.YES_NO_OPTION);
    
           if(n==JOptionPane.YES_OPTION)
           {
               n_client.inviaPVT("^" + this.nickname.toString());
               isClientConnected = false;
               listModel.removeAllElements() ;
               n_client.closePVT();
               //System.exit(0);
               System.out.println("l'utente ha abbandonato la chat");
               setVisible(false);
            }
        }

  4. #4
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    codice:
      /**
        *
        * @param utenteSel
        * @throws NullPointerException
        * @throws IOException
        * DEVO AGGIUNGERE COME CONTROLLO CHE SE C'E' PIù DI UN UTENTE IN CHAT PRIVATA
        * DEVE APRIRSI UN'ALTRA FINESTRA (EVENTUALMENTE INVITI A CHAT PRIVATA)
        */
    
       public void EntraInChatPrivata(String utenteSel) throws NullPointerException, IOException
       {
            try{
                this.nickname=utenteSel;
                n_client = new chatApplet.ClientChat();
                n_client.startPVT();
    
                n_client.inviaPVT("_" + utenteSel);
                String strReceived = n_client.MessaggiPVTRicevuti();
                System.out.println(strReceived);
    
                strReceived  = strReceived.substring(7); // Ricava la lista utenti
    
                if(! strReceived.equals("") )
                {
                   String[] users = strReceived.split("_");
    
                   for (int i = 0; i < users.length ; i++)
                   {
                      if(users.length<=1){
                        listModel.insertElementAt(users[i],listModel.getSize());
                      }
                     else
                     {
                        JOptionPane.showMessageDialog(null, "Utente impegnato in altra chat!", "alert",
                        JOptionPane.CANCEL_OPTION);
                        return;
                     }
                   }
                }
                else
                {
                  listModel.insertElementAt(nickname,listModel.getSize());
    
                }
              isClientConnected=true;
              ThreadMessaggiPVTRicevuti();
           }
           catch(Exception ex){
                 n_client.closePVT();
           }
       }
    
       public void ThreadMessaggiPVTRicevuti() throws IOException
       {
          ReceivedPVTClientMessagge toRun=new ReceivedPVTClientMessagge();
          Thread rcvThread = new Thread(toRun);
          rcvThread.start();
    
       }
    
    
       public class ReceivedPVTClientMessagge implements Runnable
       {
          /*
           * Metodo che a partire da un messaggio ricevuto dal client,
           * stampa a video un messaggio relativo alla connessione/disconnessione
           * di un utente e i relativi messaggi inviati
           */
    
          /**
           * Metodo che stampa a video lo stato di un utente ed i relativi messaggi
           */
    
          public void run()
          {
             String strLastText;
             String strReceived;
             while(isClientConnected)
             {
                try
                {
                   strReceived = n_client.MessaggiPVTRicevuti();
    
                   /*
                    * Se la stringa ricevuta è null, probabilmente
                    * il client e' stato disconnesso. Alla successiva iterazione
                    * verrà_ concluso il ciclo while.
                    */
                   if (strReceived == null)
                      continue;
                   /*else
                   {
                       Font font;
                       font=FontChose();
                       viewmsg.setFont(font);
                       strLastText =  viewmsg.getText().equals("") ? ""
                            : viewmsg.getText() + "\n";
                      viewmsg.setText((strLastText) + (strReceived));
                   }*/
                    else if(/*strReceived.startsWith("Utente Privato")
                         ||strReceived.startsWith("_")*/
                         strReceived.startsWith("Rimuovi Utente")
                         ||strReceived.contains("^")
                         ||strReceived.startsWith("Nuovo Utente")
                         ||strReceived.contains("~"))
                    {
                        break;
                    }
                    else
                    {
                       Font font;
                       font=FontChose();
                       viewmsg.setFont(font);
                       strLastText =  viewmsg.getText().equals("") ? ""
                            : viewmsg.getText() + "\n";
                       viewmsg.setText((strLastText) + (strReceived));
                    }
    
                 }
                catch (Exception exc)
                {
                   exc.getCause();
                }
             }
          }
       }
    
      public static void main (String[] args) throws IOException {
        PrivateChat pvt = new PrivateChat();
    
      }
    
    }
    Ho un pò di problemi nella corretta visualizzazione dei messaggi

    un utente scambia correttamente i messaggi in chat pubblica ed in chat privata, ma se un utente si collega in chat dopo che altri utenti sono collegati in chat pubblica, se uno di questi utenti scrive un messaggio in chat privata mi va a finire in quella pubblica;

    Quando avvio una chat privata non riesco ad alternare nella visualizzazione delle 2 finestre i nome dell'utente invitato con l'altro utente;

    Inizialmente non avevo problemi con questa cosa, ma cambiando notevolmente il programma mi sono accorto solo ora, che l'eliminazione e quindi l'aggiornamento delle liste utenti.

    PURTROPPO NON POSSO INDENTARE MEGLIO PERCHE' SONO TANTE LE RIGHE DI CODICE..

  5. #5
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,328
    Originariamente inviato da marshall86
    Ho un pò di problemi nella corretta visualizzazione dei messaggi
    E nel regolamento (al punto 6) è anche indicato un modo per non avere questi problemi. Ovvero, entrare nel corpo del messaggio che stai scrivendo, scrivere

    [CODE]
    premere invio, incollare tutto il codice, posizionarsi alla fine del codice e scrivere
    [/CODE]

    .

    Semplice, no?


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  6. #6
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    L'ho fatto ma mi viene così...

  7. #7
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    Originariamente inviato da marshall86
    L'ho fatto ma mi viene così...
    ok ora ci sono riuscito

  8. #8
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    Qualcuno sa come aiutarmi? non so più come comportarmi per risolvere questi problemi..

  9. #9
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,328
    La questione della chat pubblica e privata va risolta a livello di protocollo di comunicazione. Nel messaggio che viene inviato dal client verso il server, infatti, dovrebbe esserci un indicazione del fatto che quel messaggio è pubblico o privato. Se privato, dovrebbe anche esserci l'indicazione del destinatario.

    Il server dovrebbe semplicemente smistare i messaggi pubblici a tutti, mentre quelli privati SOLO al destinatario, il quale riceve il messaggio e lo discrimina sempre tramite l'indicazione contenuta nel messaggio stesso.

    A questo punto, il client sa se deve stamparlo sulla finestra pubblica o su quella privata (e quale, perchè l'utente potrebbe avere aperto più di una comunicazione privata con diversi utenti).

    Non ho letto tutto il tuo codice, ma non mi sembra che tu abbia adottato questo tipo di soluzione, ma che il tutto sia relegato ad una serie di stringhe con particolari formati (può andare bene, ma diventa difficile da gestire).

    Diversi anni fa ho realizzato una chat di questo tipo e, se può esserti d'aiuto, ti posso inviare il codice (basta che tu mi mandi un PVT con l'indirizzo e-mail).


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  10. #10
    Utente di HTML.it
    Registrato dal
    Jul 2007
    Messaggi
    107
    puoi provare ad esegeuire il mio codice? ho pochi giorni ancora e non ho tempo quindi di modificare drasticamente il progetto perchè lo devo consegnare.. quindi stando a quello che ho fatto dove è che sbaglio?

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 © 2026 vBulletin Solutions, Inc. All rights reserved.