IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AWT/Swing Java Discussion :

Probleme d'utilisation des sockets avec Swing


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre régulier
    Inscrit en
    Août 2005
    Messages
    8
    Détails du profil
    Informations forums :
    Inscription : Août 2005
    Messages : 8
    Par défaut Probleme d'utilisation des sockets avec Swing
    Bonjour,

    En faite, je. suis entrain de développer un petit programme de chat (client/serveur).
    mon problème se résume que une fois le client établis la connexion et commence à lire le flux d'entrée, l'interface swing se plante, et les champs de texte ne me permettent ni d'y ecrire ni aussi de visualiser le flux d'entrée de la socket.

    NB: quand j'affiche le texte arrivant via system.out.println je le reçoit, donc le problème réside dans swing et son interface qui se plante une fois la lecture de flux commence.

    aidez moi svp...


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    
    
    import java.io.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.*;
    
    public class ClientInt extends javax.swing.JFrame {
        private Socket client;
        BufferedReader br;
        String message;
        Timer timer;
        /** Creates new form ClientInt */
        public ClientInt() {
            initComponents();
        }
        
        /** 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.
         */
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            Connect = new javax.swing.JButton();
            port = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            host = new javax.swing.JTextField();
            jScrollPane1 = new javax.swing.JScrollPane();
            Sended = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            toSend = new javax.swing.JTextArea();
            Send = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            Connect.setText("connect");
            Connect.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ConnectActionPerformed(evt);
                }
            });
    
            port.setFont(new java.awt.Font("Tahoma", 1, 11));
    
            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
            jLabel1.setText("Port");
    
            jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
            jLabel2.setText("Host");
    
            host.setFont(new java.awt.Font("Tahoma", 1, 11));
    
            Sended.setColumns(20);
            Sended.setRows(5);
            jScrollPane1.setViewportView(Sended);
    
            toSend.setColumns(20);
            toSend.setRows(5);
            jScrollPane2.setViewportView(toSend);
    
            Send.setText("Send");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(54, 54, 54)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 98, Short.MAX_VALUE)
                                    .addComponent(Connect))
                                .addComponent(jLabel2)))
                        .addComponent(Send, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Connect)
                        .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(Send)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>                        
    
        private void ConnectActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // TODO add your handling code here:
            try{
            client = new Socket(host.getText(),Integer.parseInt(port.getText()));   // l'etablissement de la connexion
            JOptionPane.showMessageDialog(null, "connexion etablie");  //une fois etablie on aura le message
            br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            
          timer = new Timer(1000, new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              try{
                message =br.readLine();
              }
              catch(Exception e2)
              {
                  
              }
               if(message == null)
                   System.exit(0);
               message = Sended.getText()+ message +"\n";
                Sended.setText(message);
                
          }
        });
        timer.start();
            /*while (true) {
               message =br.readLine();
               if(message == null)
                   break;
               message = Sended.getText()+ message +"\n";
                Sended.setText(message);
                //tt = new TextModifier(message);         // thread de lecture du message
                
               //break;
              System.out.println("ECHO = " + message);
            }*/
            } 
            catch(Exception e){
                 JOptionPane.showMessageDialog(null,"probleme de connexion, verifier " +
                         "la validité et la disponibilité du numéro du port et la nom du serveur"); ///en cas d'erreur 
            }
        }                                       
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ClientInt().setVisible(true);
                }
            });
        }
        
        
        // Variables declaration - do not modify                     
        private javax.swing.JButton Connect;
        private javax.swing.JButton Send;
        private javax.swing.JTextArea Sended;
        private javax.swing.JTextField host;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JTextField port;
        private javax.swing.JTextArea toSend;
        // End of variables declaration                   
        
       
    }

  2. #2
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    En même temps en effectuant une opération de lecture bloquante sur une socket dans le thread Swing, il est normal que les composants ne se redessinent plus .

    Aller hop un poil de lecture pour toi, tu comprendras pourquoi ton interface ne réagis plus: http://gfx.developpez.com/tutoriel/j...ing-threading/

  3. #3
    Membre régulier
    Inscrit en
    Août 2005
    Messages
    8
    Détails du profil
    Informations forums :
    Inscription : Août 2005
    Messages : 8
    Par défaut le robléme persiste encore...
    Merci pour le lien,

    en faite j'ai compris d'ou viens le probleme, mais our e resoudre j'ai pas arriver...

    meme si j'utilise un nouveau tread ou InvokeLater, cela persiste, et ça m'afolle...

    à l'aide SVP....

  4. #4
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    Bon grosso modo, tout code concernant la socket doit se trouver dans un thread, pas celui de l'interface graphique (donc le code de ton connectActionPerformed doit démarrer un thread dans lequel tu réalises la connexion via la socket). Par la suite, tu devras modifier l'interface depuis ce thread. Pour celà il faut passer par la méthode SwingUtilities.invokeLater(Runnable R). Dans le runnable tu inclues le code qui va modifier l'interface graphique. En procédant de cette manière tu n'auras pas le moindre problème. (relis le tuto dont je t'ai filé le lien).

  5. #5
    Membre régulier
    Inscrit en
    Août 2005
    Messages
    8
    Détails du profil
    Informations forums :
    Inscription : Août 2005
    Messages : 8
    Par défaut ca marche pas encore....:(
    bonjour

    j'ai essayé de faire comme tu m'avez proposé, mais j'ai toujours le même problème...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    package chatpp;
    
    /*
     * ClientInt.java
     *
     * Created on 2 novembre 2008, 21:21
     */
    
    
    
    /**
     *
     * @author  The prince Sam
     */
    
    import java.io.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.*;
    
    public class ClientInt extends javax.swing.JFrame {
        private Socket client;
        BufferedReader br;
        String message;
        Timer timer;
        /** Creates new form ClientInt */
        public ClientInt() {
            initComponents();
        }
        
        /** 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.
         */
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            Connect = new javax.swing.JButton();
            port = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            host = new javax.swing.JTextField();
            jScrollPane1 = new javax.swing.JScrollPane();
            Sended = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            toSend = new javax.swing.JTextArea();
            Send = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            Connect.setText("connect");
            Connect.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ConnectActionPerformed(evt);
                }
            });
    
            port.setFont(new java.awt.Font("Tahoma", 1, 11));
    
            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
            jLabel1.setText("Port");
    
            jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
            jLabel2.setText("Host");
    
            host.setFont(new java.awt.Font("Tahoma", 1, 11));
    
            Sended.setColumns(20);
            Sended.setRows(5);
            jScrollPane1.setViewportView(Sended);
    
            toSend.setColumns(20);
            toSend.setRows(5);
            jScrollPane2.setViewportView(toSend);
    
            Send.setText("Send");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(54, 54, 54)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 98, Short.MAX_VALUE)
                                    .addComponent(Connect))
                                .addComponent(jLabel2)))
                        .addComponent(Send, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Connect)
                        .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(Send)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void ConnectActionPerformed(java.awt.event.ActionEvent evt) {                                        
            
            new Thread(new Runnable() {
          public void run() {
                try{
            client = new Socket(host.getText(),Integer.parseInt(port.getText()));   // l'etablissement de la connexion
            JOptionPane.showMessageDialog(null, "connexion etablie");  //une fois etablie on aura le message
            br = new BufferedReader(new InputStreamReader(client.getInputStream()));
              } 
            catch(Exception e){
                 JOptionPane.showMessageDialog(null,"probleme de connexion, verifier " +
                         "la validité et la disponibilité du numéro du port et la nom du serveur"); ///en cas d'erreur 
            } 
      
             
    timer = new Timer(1000, new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              
              try{
            message =br.readLine();
              }
              catch(Exception e2)
              {
                  
              }
               if(message == null)
                   System.exit(0);
               
                     SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                message = Sended.getText()+ message +"\n";
                Sended.setText(message);
              }});
                
          }
         
        });
        timer.start();
          }
      }).start();
    
            
        }                                       
        
      
        
        
        // Variables declaration - do not modify
        private javax.swing.JButton Connect;
        private javax.swing.JButton Send;
        private javax.swing.JTextArea Sended;
        private javax.swing.JTextField host;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JTextField port;
        private javax.swing.JTextArea toSend;
        // End of variables declaration
        
      
    }
    et ça plante encore...:'(

    aidez mois SVP, ou réside le probleme??!!!, je ne comprend plus rien ...

    Merci d'avance..

  6. #6
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    C'est toujours le même problème tu essaies de faire une opération de lecture sur ta socket depuis l'EDT. En effet l'actionPerformed du timer se déroule dans l'EDT. Or les opérations de lecture sur socket sont bloquantes (le déroulement du code se stoppe complêtement quans il arrive à l'instruction de lecture).
    Donc il faut que tous les br.readLine se déroule depuis un thread, et non depuis l'actionPerformed du timer.

Discussions similaires

  1. [Débutant] utiliser des sockets avec le port 23
    Par nour_dhaouadi dans le forum C#
    Réponses: 1
    Dernier message: 14/04/2013, 05h06
  2. [Socket][C++]Utilisation des sockets sur internet
    Par ChriGoLioNaDor dans le forum Développement
    Réponses: 8
    Dernier message: 13/01/2006, 21h38
  3. [MFC] Faible utilisation des sockets via les MFC ?
    Par Yellowmat dans le forum MFC
    Réponses: 1
    Dernier message: 25/08/2005, 17h15
  4. [CF][PPC/VB.NET] Comment utiliser les Socket avec Pocket PC ?
    Par joefou dans le forum Windows Mobile
    Réponses: 5
    Dernier message: 17/05/2005, 14h24
  5. utilisation des sockets sous windows
    Par Tupac dans le forum Réseau
    Réponses: 2
    Dernier message: 21/12/2002, 18h24

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo