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

Concurrence et multi-thread Java Discussion :

ArrayList de Thread..


Sujet :

Concurrence et multi-thread Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2005
    Messages : 2
    Par défaut ArrayList de Thread..
    Bonjour à tous, je me suis lancé dans la programmation d'un serveur TCP java,
    Chaque client est géré par un thread de la classe ThreadClient :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    public class ThreadClient extends Thread {
              ...
    }
    Chaque clients lors de sa creation est stoqué dans un tableau et je lui assigne donc un ID qui est sa place dans le tableau, seulement voila,
    imaginons 3 client connectés, donc les ID seront : 0,1,2
    le client d'ID 1 se deconnecte il reste donc 2 client d'ID : 0,2

    Du coup je dois changer les ID des clients qui se trouves apres le 1.
    pour cela j'ai créé une methode changeId(int id) dans la classe ThreadClient
    seulement voila il faut au préalable que je fasse un tableau de mes thread client
    afin de le parcourir et d'appliquer changeID a chaque threadclient je procede de cette maniere :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    private static List<ThreadClient> tlist = new ArrayList();
    puis a chaque connection de client :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    Thread threadclient = new ThreadClient(client,clients.indexOf(client));                                         
                        threadclient.start();                          |cannot find symbol
                        tlist.add(threadclient); <-------- erreur|symbol:method add(...
                                                                             |location:interface...
    je bloque ici je ne comprend pas pourquoi ca ne marche pas, jespere que vous pourez me donner un coup de main, merci d'avance.

  2. #2
    Membre averti
    Profil pro
    Inscrit en
    Mai 2002
    Messages
    57
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2002
    Messages : 57
    Par défaut
    On ne comprend pas trop ton problème. Met le code de ton thread et le code qui gère les nouvelles connections, et met a par l'erreur qui s'affiche quand tu essaye de te connecter.

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2005
    Messages : 2
    Par défaut
    Bon le code est un peu long mais je n'est pas le courage de supprimer ce qui inutile :

    Classe Main qui gère les connections :

    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package serveur2;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    /**
     *
     * @author Sephiroth
     */
    public class Main {
    private static List<Socket> clients = new ArrayList();
    private static List<ThreadClient> tlist = new ArrayList();
    private static int nbclients = 0;
        public static void main(String[] args) {
            try {
                System.out.println("† HellGate † : Selectionnez le port du portail : ");
                BufferedReader cmd = new BufferedReader(new InputStreamReader(System.in));
                int port = Integer.parseInt(cmd.readLine());
                System.out.println("† HellGate † : Ouverture du portail sur le port : "+port);
                try {
                    ServerSocket serveur = new ServerSocket(port);
                    System.out.println("† HellGate † : Portail ouvert avec succes sur le port : "+port);
                    System.out.println("† HellGate † : Tapez <close> pour fermer le portail.");
                    Thread commandes = new Commandes();
                    commandes.start();
                    while(true){
                        Socket client;
                        client=serveur.accept();
                        PrintWriter out;
                        out=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
                        nbclients++;
                        clients.add(client);
     
                        System.out.println("† HellGate † : Connection de "+client.getInetAddress().getHostAddress()+" (ID="+clients.indexOf(client)+")"+" sur le portail !");
                        System.out.println("† HellGate † : Nombre de clients connectés : "+nbclients);
                        out.println("");out.flush();
                        out.println("");out.flush();
                        out.println("                                   I     IIHH. ");out.flush();
                        out.println("                  .HHHHHHHHI.   :       : IHHHMHHIIH.");out.flush();
                        out.println("              IIIIHI.HIIIH      :.HI    H I I.H:H:H:..II ");out.flush();
                        out.println("           .I:.HI:.H:.::H ..   H HH H        :.H.H..I.:..H  ");out.flush();
                        out.println("         IH::HI::IH::.M.H      H.H:.         H.I..I...I:::.I");out.flush();
                        out.println("       :IIII:.I:I::I:I..H      HHIHHM.       H:.H::I.::H:II:: ");out.flush();
                        out.println("      IIIII:.I:HIIII:H:.:.    :I:HH::IH      H::::::H:IIH:III:I   ");out.flush();
                        out.println("    :IIHHI::IIIHIIIIII:::H    I:    ::HH    H:::H::IH::IIIIIIII:  ");out.flush();
                        out.println("  IHIMMHHIIHIIIHHHHIIHIIII:H:    I:::IH.  IHIIHI:IIHHHIIIIIHIHHHHI ");out.flush();
                        out.println(" HMIHMMHHIHHIHIIHMMMIIIIIIIIHHH..:HIIH. HHIIIIHIHIHM.HIIIHIIIHHMMHI ");out.flush();
                        out.println(" HHIMHMHIHMMHH     HHHIHHHHIIIIH:I::MIHHIIIHHHHHIH    IIHHHIIIHMMMHI ");out.flush();
                        out.println("    :IMMHMMMHH      HHHI   HIHMI:IIH::.IIHH.  HHH     HIIHHHIIHMM ");out.flush();
                        out.println("     MHIMMMMHH       H      HMHH:IIHIII:I             :IHHHHHHMM ");out.flush();  
                        out.println("     IIHHMMHMI            HHH   :IIHHH:H              IIHHHHHIHH ");out.flush();
                        out.println("      IHMHMMHII                 IIIH::                HHHMHMMHIH ");out.flush();
                        out.println("      I.HHHHMH:                 H:IHM :               HHMMMMMMHH ");out.flush();
                        out.println("      I    :MHH                HH:MH:H               HHMMH..:HHM  ");out.flush();
                        out.println("             MH                MI:MH:I               IMM       H ");out.flush();
                        out.println("              H:              IH:MMIMM              .HH   ");out.flush();
                        out.println("               H              IHMIHIMH              IM ");out.flush();
                        out.println("                H              IH:HMH              IH");out.flush();
                        out.println("                               HIIIII");out.flush();
                        out.println("                               :IHHH");out.flush();
                        out.println("                              :IH");out.flush();
                        out.println("                             IIM        .HH");out.flush();
                        out.println("                             II.      :I    H");out.flush();
                        out.println("                             II              M ");out.flush();
                        out.println("                             HI.             H");out.flush();
                        out.println("                              :H            MI");out.flush();
                        out.println("                              IIM          MH");out.flush();
                        out.println("                               .II      HHH");out.flush();
                        out.println("                                  IIIIII");out.flush();
                        out.println("");out.flush();
                        out.println("     † HellGate † : Bienvenue !");out.flush();
                        out.println("     † HellGate † : Tapez <quit> pour vous deconnecter. ");out.flush();
                        Thread threadclient = new ThreadClient(client,clients.indexOf(client));                                         
                        threadclient.start();
                        tlist.add(threadclient);  <------- ERREUR ICI*
                    }
                }catch (IOException e){
                    System.out.println("Erreur : "+e.getMessage());
                }
            } catch (IOException ex) {
                System.out.println("Erreur : "+ex.getMessage());
            }
     
        }
        public static void deleteClient(int id){
            nbclients--;
            System.out.println("† HellGate † : Le client "+clients.get(id).getInetAddress().getHostAddress()+" (ID="+id+")"+" s'est déconnecté !");
            System.out.println("† HellGate † : Nombre de clients connectés : "+nbclients);
            clients.remove(id);
     
        }
         synchronized public static void sendAll(String msg,int id){
            PrintWriter outall;
            try{
              if (id==-1){
                  for (int i=0;i<clients.size() ;i++){ 
                      outall = new PrintWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
                      outall.println(msg);
                      outall.flush();
                  } 
              }else{
              for (int i=0;i<clients.size() ;i++){  
                  if (i!=id){
                      outall = new PrintWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
                      outall.println(clients.get(id).getInetAddress().getHostAddress()+" (ID="+id+") :"+msg);
                      outall.flush();
                  }
                  }
     
              }
     
            }catch(IOException exx){
                  System.out.println("Erreur : "+exx.getMessage());
            }
        }
     
     
    }
    Classe ThreadClient prenant en charge le client :

    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package serveur2;
     
    import java.io.*;
    import java.net.*;
     
    /**
     *
     * @author Sephiroth
     */
    public class ThreadClient extends Thread {
        Socket client;
        int id;
        public ThreadClient(Socket client,int id){this.client=client;this.id=id;}
        @Override
        public void run(){
            try{
                String ligne;
                PrintWriter out;
                out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
                BufferedReader in;
                in =new BufferedReader(new InputStreamReader(client.getInputStream()));
                while(true){
                    ligne = in.readLine();
                    if (ligne.equals("quit")){
                        out.println("       † HellGate † : Vous allez etre deconnecte !");out.flush();
                        out.println("       † HellGate † : Connection perdue !");out.flush();
                        client.close();
                        break;
                    }
                    System.out.println(client.getInetAddress().getHostAddress()+" (ID="+id+") :"+ligne);
                    Main.sendAll(ligne, id);
                }
            }catch(IOException ex){
                System.out.println("† HellGate † : Erreur : "+ex.getMessage());
            }finally{
                Main.deleteClient(id);
            }
        }
        public void changeId(int newid){
            this.id=newid;
        }
    }
    et enfin classe Commande en attente des commandes serveur :

    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package serveur2;
     
    import java.io.*;
     
    /**
     *
     * @author Sephiroth
     */
    public class Commandes extends Thread {
        @Override
        public void run(){
            try{
                BufferedReader cmd;
                cmd = new BufferedReader(new InputStreamReader(System.in));
                while(true){
                    if (cmd.readLine().equals("close")){
                        System.out.println("† HellGate † : Fermeture du portail.");
                        Main.sendAll("† HellGate † : Fermeture du portail, vous allez etre deconnecte.",-1);
                        System.exit(0);
                    }
                }
            }catch(IOException ex){
                System.out.println("Erreur : "+ex.getMessage());
            }
        }
    }
    *ERREUR : cannot find symbol
    symbol : method add(java.lang.Thread)
    location : interface java.util.List<serveur2.ThreadClient>

    Je précise que j'utilise netbeans..

  4. #4
    Membre chevronné Avatar de Jabbal'H
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Octobre 2004
    Messages
    403
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Ille et Vilaine (Bretagne)

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

    Informations forums :
    Inscription : Octobre 2004
    Messages : 403
    Par défaut
    pas testé mais peut etre que au lieu de
    tu pourrais mettre
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    List<? extends Thread> ...

  5. #5
    Membre très actif
    Inscrit en
    Mars 2008
    Messages
    283
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 283
    Par défaut
    1) ne fait pas de flush après chaque ligne, un seul après ton joli dragon ASCII suffit.

    2) Tu a une liste de ThreadClient et tu lui donne un Thread ... (si A est un ThreadClient alors A est aussi un Thread mais la réciproque est fausse)

    remplace
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Thread threadclient = new ThreadClient(client,clients.indexOf(client));
    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ThreadClient threadclient = new ThreadClient(client,clients.indexOf(client));

Discussions similaires

  1. Thread et ordre d'insertion dans un arrayList
    Par cdtkoenig dans le forum Concurrence et multi-thread
    Réponses: 2
    Dernier message: 28/10/2009, 13h32
  2. [C#] ArrayList, For each et threads
    Par Vlad_Oliv dans le forum C#
    Réponses: 6
    Dernier message: 09/07/2008, 09h47
  3. Réponses: 5
    Dernier message: 27/02/2008, 17h27
  4. Tri multi-threadé
    Par Tifauv' dans le forum C
    Réponses: 8
    Dernier message: 28/06/2007, 09h00
  5. [Kylix] Pb de Thread !!
    Par Anonymous dans le forum EDI
    Réponses: 1
    Dernier message: 25/04/2002, 13h53

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