Chat application ne répond pas

Résolu
GFaDd Messages postés 2 Date d'inscription   Statut Membre Dernière intervention   -  
GFaDd Messages postés 2 Date d'inscription   Statut Membre Dernière intervention   -
Bonjour,

Je suis en train de développer une application client serveur(en localhost) sous netbeans, lorsque j'exécute mon Jframe serveur puis le Jframe client tout va bien, mais le problème c'est que lorsque je fait appel à mon client depuis une autre Jframe(qui contient un bouton "Appeler"), rien ne se passe,ni le serveur, ni le client envoie ou reçoit, est ce qu'il y'a quelqu'un qui peut m'aider, merci.
le code Client:
package javaapplication7;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;


public class Client extends javax.swing.JFrame {

static Socket s;
    static DataInputStream dun;
    static DataOutputStream dout;
    public Client() {
        initComponents();
    }


private void initComponents() {

jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        msg_area = new javax.swing.JTextArea();
        msg_text = new javax.swing.JTextField();
        msg_send = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

msg_area.setColumns(20);
        msg_area.setRows(5);
        jScrollPane1.setViewportView(msg_area);

msg_text.setText("jTextField1");

msg_send.setText("jButton1");
        msg_send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                msg_sendActionPerformed(evt);
            }
        });

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                    .addComponent(msg_text))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(msg_send)
                .addGap(44, 44, 44))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(56, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(msg_send)
                .addGap(100, 100, 100))
        );

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

pack();
    }// </editor-fold>                        

private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {                                         
                 try {
        String msgout = "";
        msgout = msg_text.getText().trim();
        dout.writeUTF(msgout);
        } catch (Exception e) {

}
    }                                        

/**


* @param args the command line arguments

*/
public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.


* For details see [http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html] 

*/
try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

/* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Client().setVisible(true);
            }
        });
        try{
          s = new Socket("localhost", 80);
          dun = new DataInputStream(s.getInputStream());
          dout = new DataOutputStream(s.getOutputStream());
          String msgin = "";

while(!msgin.equals("Exit")){
              msgin = dun.readUTF();
              msg_area.setText(msg_area.getText().trim()+"\n serveur :\t"+msgin); 
          }
         }catch(Exception e){}
    }

// Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTextArea msg_area;
    private javax.swing.JButton msg_send;
    private javax.swing.JTextField msg_text;
    // End of variables declaration                   
}>


le code serveur:

package javaapplication7;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Serveur extends javax.swing.JFrame {
static ServerSocket ss;
    static Socket s;
    static DataInputStream dun;
    static DataOutputStream dout;
public Serveur() {
        initComponents();
    }
 private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
        String msgout = "";
        msgout = msg_text.getText().trim();
        dout.writeUTF(msgout);
        } catch (Exception e) {

}
    }               
 public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Serveur().setVisible(true);
            }
        });
         String msgin = "";
        try{
         ss = new ServerSocket(80); 
         s = ss.accept();
         dun = new DataInputStream(s.getInputStream());
         dout = new DataOutputStream(s.getOutputStream());
         while(!msgin.equals("Exit")){
             msgin = dun.readUTF();
             msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
         }
        }catch(Exception e){}
    }

// Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTextArea msg_area;
    private javax.swing.JButton msg_send;
    private javax.swing.JTextField msg_text;
    // End of variables declaration                   
}>


le code du Jframe qui va appeler le client:

package javaapplication7;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import static javaapplication7.Serveur.s;
public class Tes extends javax.swing.JFrame {
public Tes() {
        initComponents();
    }
@SuppressWarnings("unchecked")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      Client cl = new Client();
       cl.setVisible(true);

}         
public static void main(String args[]) throws IOException {
java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

}
        });

}

// Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}
A voir également:

2 réponses

tarek_dotzero Messages postés 817 Date d'inscription   Statut Membre Dernière intervention   122
 
Bonjour,

Le code qui lance le serveur et le code qui crée la Socket client sont dans les méthodes main, cette méthode est exécutée si on exécute la classe pas si on crée une instance.

En d'autre termes, lorsque vous faites :

       Client cl = new Client();
       cl.setVisible(true);


Vous créez la fenêtre et l'afficher, le code :

        String msgin = "";
        try{
             ss = new ServerSocket(80); 
             s = ss.accept();
             dun = new DataInputStream(s.getInputStream());
             dout = new DataOutputStream(s.getOutputStream());
             while(!msgin.equals("Exit")){
                 msgin = dun.readUTF();
                 msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
             }
        }catch(Exception e){}


N'est jamais exécuté.

La solution : déplacer le code qui se charge de dialogue client/serveur dans le client et dans le serveur de la métode main vers le constructeur de la classe pour garantir son exécution lorsque vous créez une nouvelle instance (avec un "new").

Bon Courage.
0
GFaDd Messages postés 2 Date d'inscription   Statut Membre Dernière intervention  
 
Merci tarek(même si c'est un peu retard), Le problème est résolu avec l'aide d'un professeur à l'université,les changements apportés sont tels que:
public class Client extends javax.swing.JFrame implements Runnable{
Au lieu de:
public class Client extends javax.swing.JFrame {
au niveau du main du client:
Thread th = new Thread(new Client()); th.start();
au lieu du:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Client().setVisible(true);
} });
try{ s = new Socket("localhost", 80);
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while(!msgin.equals("Exit")){
msgin = dun.readUTF();
msg_area.setText(msg_area.getText().trim()+"\n serveur :\t"+msgin); } }catch(Exception e){} }
puis il a ajouté en fin ce code là:
@Override public void run() {
try {
s = new Socket("localhost", 80);
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
while (!msgin.equals("Exit")) {
msgin = dun.readLine();
msg_area.setText(msg_area.getText()+"\n"+msgin); // s.close(); }
} catch (Exception e) { System.out.println("0001"); e.printStackTrace(); }
}
}
et enfin le code du bouton dans le Jframe qui va appeler le client:
Thread th = new Thread(new Client());
th.start();
0