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

avec Java Discussion :

Thread sur serveur


Sujet :

avec Java

  1. #1
    Membre confirmé Avatar de hugoclo
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    615
    Détails du profil
    Informations personnelles :
    Âge : 48
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Décembre 2007
    Messages : 615
    Points : 480
    Points
    480
    Par défaut Thread sur serveur
    Bonjour,
    J'essaye désespérément de faire un serveur pour communiquer avec un client.
    Je souhaite envoyer un élément de ma liste(listenumero) attendre la réponse du client, marquer dans mon jtextpane la réponse puis passer à l'élément suivant de ma liste.
    Quand je clique sur mon bouton le premier message par contre je n'arrive pas à écouter la réponse.
    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
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    public class Sms extends javax.swing.JDialog {
        private ArrayList Listenumero = new ArrayList();
        String inputLine, outputLine;
        private int count;
        static String remoteAddr;
        static String bienpa = "";
        static int localPort = 8080;
        static int remotePort = 8080 ;
        DatagramSocket socket;
        private Pattern pattern;
        private Matcher matcher;
     
        private static final String IPADDRESS_PATTERN = 
    		"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
     
     
        /**
         * Creates new form Sms
         */
        public Sms(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
     
            Listenumero.add("06XXXXXXXX");
            Listenumero.add("06XXXXXXXX");
            Listenumero.add("06XXXXXXXX");
            Listenumero.add("06XXXXXXXX");
            try
                {
                        InetAddress thisIp = InetAddress.getLocalHost();
                        Lbl_Ip_Pc.setText("IP à mettre sur le tel :"+thisIp.getHostAddress());
                }
                    catch(UnknownHostException e)
                    {
                        e.printStackTrace();
                    }
            jFormattedTextField1.getDocument().addDocumentListener(new DocumentListener() {
                    private void updateData() {
                       if(validate(jFormattedTextField1.getText())){
                           jButton1.setEnabled(true);
                           remoteAddr = jFormattedTextField1.getText();
                       }else{
                           jButton1.setEnabled(false);
                           remoteAddr = jFormattedTextField1.getText();
                       }
                    }
                @Override
                public void insertUpdate(DocumentEvent e) {
                updateData();
                }
     
                @Override
                public void removeUpdate(DocumentEvent e) {
                updateData();
                }
     
                @Override
                public void changedUpdate(DocumentEvent e) {
                updateData();
                }
     
            });
            jFormattedTextField1.setText("");
        }
     
            public boolean validate(final String ip){
                 pattern = Pattern.compile(IPADDRESS_PATTERN);
    	  matcher = pattern.matcher(ip);
    	  return matcher.matches();	    	    
        }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            try {
     
                DatagramSocket socket = new DatagramSocket ();
                byte[] buf = new byte[256];
                String outputLine = Listenumero.get(count).toString() +";"+ txt_msg.getText ()+";";
                buf = outputLine.getBytes ();
                InetAddress address = InetAddress.getByName (remoteAddr);
                DatagramPacket packet = new DatagramPacket (buf , buf.length, address, remotePort);
                System.out.println ("Attention Départ/n");
                socket.send (packet);
                System.out.println ("Départ Pc/n");
     
                count++;
            } catch (SocketException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnknownHostException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
            }
            updateJtextarea();
        }                                        
    //***********************************************************************************************************
             public void updateJtextarea(){
        SwingWorker<Void,String> sw = new SwingWorker<Void,String>(){
        @Override
        public Void doInBackground() throws BadLocationException{
            jProgressBar1.setMaximum(Listenumero.size());
             Txt_pane.setEditable(true);
             String nonparti = "";
             publish("<==========================Début du traitement==========================>\n/1");
             boolean parti = false;
            try {
     
                int t = 0;
                        DatagramPacket packet;
     
                          byte[] buf = new byte[256];
     
     
     
                          while (true)
     
                                 {
     
                                 packet = new DatagramPacket (buf, buf.length);
     
                                 socket.receive (packet);
     
     
     
                                 String received = new String (packet.getData());
                                     System.out.println(received);
                                        if(received.equals("Ok")){
    //                                      bienpa = "Le Sms est bien parti/n";
    //                                      publish(bienpa);
                                            if(count<Listenumero.size()){
                                                send();
                                            }else{
    //                                            bienpa = "Dernier Numero/n";
    //                                            publish(bienpa);
                                                jButton1.setEnabled(true);
                                            }
                                        }else if(received.equals("Ko")){
    //                                        bienpa = "Probleme sur le n° : " + Listenumero.get(count)+"/n";
                                            send();
                                        }
     
     
                          }
     
     
     
            }  catch (IOException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
            }
            if(nonparti!=""){
                publish("\n\n\nAttention les mails suivants ne sont pas partis \ncar \n/1" );
                publish( nonparti + "\n/3");
                publish("<===========================Fin du traitement===========================>/1");
                System.out.println(nonparti);
            } else{
                publish("\n<===========================Fin du traitement===========================>/1");
            }
     
            publish("fin/100");
     
     
            return null;
                }
        @Override
        public void process(List<String> chunks){
              for (String message: chunks){
                 int i = Integer.parseInt(message.split("/")[1]);
                 String Message2 = message.split("/")[0].toString();
                    switch(i){
                        case 1:
                             appendToPane(Txt_pane, Message2, Color.BLACK);
                            break;
                        case 2:
                            appendToPane(Txt_pane, Message2+ "\n", Color.GREEN);
                            break;
                        case 3:
                            appendToPane(Txt_pane, Message2+ "\n", Color.RED);
     
                            break;
                        case 100:
                            Txt_pane.setEditable(false);
                            jProgressBar1.setValue(jProgressBar1.getValue()+1);
                   }
     
              }
        }
        };
         sw.execute();
      }
                 static void appendToPane(JTextPane tp, String msg, Color c) {
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
     
            aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
            aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
     
            int len = tp.getDocument().getLength();
            tp.setCaretPosition(len);
            tp.setCharacterAttributes(aset, false);
            tp.replaceSelection(msg);
        }
     
         private void send(){
            try {
                DatagramSocket socket = new DatagramSocket ();
                byte[] buf = new byte[256];
                String outputLine = Listenumero.get(count).toString() +";"+ txt_msg.getText ()+";";
                buf = outputLine.getBytes ();
                InetAddress address = InetAddress.getByName (remoteAddr);
                DatagramPacket packet = new DatagramPacket (buf , buf.length, address, remotePort);
                System.out.println ("Attention Départ/n");
                socket.send (packet);
                System.out.println ("Départ Pc/n");
     
                count++;
                updateJtextarea();
            } catch (SocketException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
                count++;
            } catch (UnknownHostException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
                count++;
            } catch (IOException ex) {
                Logger.getLogger(Sms.class.getName()).log(Level.SEVERE, null, ex);
                count++;
            }
         }
        /**
         * @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(Sms.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Sms.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Sms.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Sms.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the dialog */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Sms dialog = new Sms(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        @Override
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                }
            });
        }

  2. #2
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 804
    Points
    48 804
    Par défaut
    Il se passe quoi concrètement? Qu'est-ce qui déconne?

    Au passage:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
            jProgressBar1.setMaximum(Listenumero.size());
             Txt_pane.setEditable(true);
    ça n'a rien à faire dans une doInBackground, c'est de la manipulation de composants swing

  3. #3
    Membre confirmé Avatar de hugoclo
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    615
    Détails du profil
    Informations personnelles :
    Âge : 48
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Décembre 2007
    Messages : 615
    Points : 480
    Points
    480
    Par défaut
    Quand je clique sur le bouton mon client reçoit le message, me revoit Ok mais après plus rien.
    Quand je met une point d’arrêt dans updateJtextarea() je ni rentre pas.

  4. #4
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 804
    Points
    48 804
    Par défaut
    Tu as bien le message
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
                System.out.println ("Départ Pc/n");
    dans la console?

    Accessoirement je viens de voir un truc qui pue dans ton code:

    ton updateJTextArea crée un swingworker qui tourne en permanence (while(true)), qui appelle send(), qui appelle updateJTextArea, qui crée un swingWorker qui tourne en permanence, qui appelle send() qui....

    Et tout ces thread manipulement la même socket alors que c'est pas threadsafe...


    Vu que tu a mis un while, ne crée pas de nouveau thread depuis ton send, tu va juste créer des thread à l'infini qui vont foutre le boxon.

    Avoir l'output de ton serveur et ton client serait pas mal non plus

  5. #5
    Membre confirmé Avatar de hugoclo
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    615
    Détails du profil
    Informations personnelles :
    Âge : 48
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Décembre 2007
    Messages : 615
    Points : 480
    Points
    480
    Par défaut
    Oui voici la console
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    06XXXXXXXX;test;
    Attention Départ/n
    Départ Pc/n

  6. #6
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 804
    Points
    48 804
    Par défaut
    bon si tu rentre pas dans ta méthode update avec le breakpoint, c'est qu'il est pas mis sur la méthode ou que t'as pas démarrer ton code en debug. Après le System.out.println plus rien ne peut empêcher cet appel de méthode

  7. #7
    Membre confirmé Avatar de hugoclo
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    615
    Détails du profil
    Informations personnelles :
    Âge : 48
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Décembre 2007
    Messages : 615
    Points : 480
    Points
    480
    Par défaut
    Cette ligne ne donne rien
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    System.out.println(received);
    Si j'y rentre mais cela s'arrete à cette ligne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    socket.receive (packet);
    Quand je me sers de cette exemple ca marche
    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
    public class SwingChatUdpP2P extends SwingChatGUI
     
    {
     
         String inputLine, outputLine;
     
         static String remoteAddr;
     
         static int localPort, remotePort; ;
     
         public ButtonHandler bHandler; // = new ButtonHandler();
     
         DatagramSocket socket;
    private ArrayList Listenumero = new ArrayList();
     
     
         public SwingChatUdpP2P (String title) throws IOException
     
         {
     
           super (title);
     
           bHandler = new ButtonHandler ();
     
           sendButton.addActionListener (bHandler);
     
            Listenumero.add("06XXXXXXX");
            Listenumero.add("06XXXXXXX");
            Listenumero.add("06XXXXXXX");
            Listenumero.add("06XXXXXXX");
     
           socket = new DatagramSocket (localPort);
     
         }
     
     
     
         // Transmit Message
     
         private class ButtonHandler implements ActionListener
     
         {
     
           public void actionPerformed (ActionEvent event) //throws IOException
     
           {
     
                  try
     
                  {                    
     
                          DatagramSocket socket = new DatagramSocket ();
     
                          byte[] buf = new byte[256];
     
     
     
                          String outputLine = txArea.getText ();
     
     
     
                          buf = outputLine.getBytes ();
     
                          InetAddress address = InetAddress.getByName (remoteAddr);
     
                          DatagramPacket packet = new DatagramPacket (buf, buf.length, address, remotePort);
     
                          System.out.println ("About to send message");
     
                          socket.send (packet);
     
                          System.out.println ("Sent message");
     
                  }
     
                  catch (IOException e)
     
                  {
     
                  }            
     
           }
     
         }
     
     
     
         // Receive Message
     
         public void run () throws IOException
     
         {
     
                  try
     
                  {
     
                          DatagramPacket packet;
     
                          byte[] buf = new byte[256];
     
     
     
                          while (true)
     
                                 {
     
                                 packet = new DatagramPacket (buf, buf.length);
     
                                 socket.receive (packet);
     
                                 System.out.println ("Received packet");
     
                                 String received = new String (packet.getData());
     
                                        rxArea.append(received);
     
     
                          }
     
                  }
     
                  catch (IOException e)
     
                  {
     
                  }            
     
        }
     
     
     
        public static void main (String[] args) //throws IOException
     
        {
     
     
           localPort = 8080;//Integer.parseInt (args[0]);
     
           remoteAddr = "192.168.1.99";//args[1];
     
           remotePort = 8080;//Integer.parseInt (args[2]);
           try
     
           {
     
               SwingChatUdpP2P f = new SwingChatUdpP2P ("Chat UDP P2P Program");
     
     
     
               f.pack ();
     
                f.setVisible (true);
     
     
     
                  f.run ();
     
           }
     
           catch (IOException e)
     
           {
     
                  System.err.println ("Couldn't get I/O for the connection to: 194.81.104.118.");
     
                  System.exit (1);
     
           }
     
        }
     
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Code Client/serveur avec thread sur Android
    Par Narcistou dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 21/04/2011, 11h25
  2. Pb de Thread sur un serveur IIS
    Par Catsloveuse dans le forum ASP.NET
    Réponses: 7
    Dernier message: 30/06/2010, 10h09
  3. thread sur un serveur TAO
    Par manimouleLight&Magic dans le forum CORBA
    Réponses: 1
    Dernier message: 03/12/2007, 10h10
  4. Erreur de connexion à ma base sur serveur Debian - Apache
    Par GLDavid dans le forum Installation
    Réponses: 4
    Dernier message: 24/09/2003, 10h29
  5. jsp sur serveur distant
    Par petitelulu dans le forum JBuilder
    Réponses: 5
    Dernier message: 11/09/2003, 11h50

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