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

Entrée/Sortie Java Discussion :

Comment lire un fichier dans une architecture Client-Server en utilisant des Sockets en Java


Sujet :

Entrée/Sortie Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2012
    Messages : 13
    Points : 10
    Points
    10
    Par défaut Comment lire un fichier dans une architecture Client-Server en utilisant des Sockets en Java
    J'ai besoin de lire un fichier "bdd.txt" qui est placé sur une Machine virtuelle. J'ai fais une application client/server en Java. Le server.java est sur la VM avec la "Base de données" (le fichier bdd.txt dans le même dossier), et mon client.java est sur Win7.

    Jusque ici j'ai donc séparé mon code en 2 fichier (Client/Server) et la connexion fonctionne bien entre mon Win7 et ma VM Ubuntu. Lorsque je lance le server depuis la VM, il écoute sur un port. Puis de retour sur Windows, je lance le client et la connexion s'établie bien entre les deux. Donc je peux communiquer comme il faut à l'aide de :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    socket = new Socket("my VM ip address",portNumber);

    Mon problème c'est que je ne sais pas comment adapter mon code pour y lire le fichier "bdd.txt" présent sur ma VM.


    Nom : EVnd8.png
Affichages : 756
Taille : 317,0 Ko
    Le serveur fonctionne bien.


    Nom : client1.png
Affichages : 708
Taille : 202,4 Ko
    Le client aussi. Ensuite l'application se lance, mais je ne peux pas lire le fichier avec ce code.


    Nom : app1.png
Affichages : 770
Taille : 192,2 Ko
    Dès que je clique sur "OK", l'app se lance, donc aucun problème de connexion entre client et serveur, mais je ne peux pas vérifier si un Pin saisi est bon ou pas puisque quand je clique sur le boutton "OK"à côté du JPasswordField, rien ne se passe. Donc j'ai l'impression que mon "new Client()" n'est pas fonctionnel et que ma méthode "readPinsData()" n'est jamais appelé.

    Comment je peux modifier ca dans ce type d'architecture ?

    Voici Client.java :

    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
    import java.awt.BorderLayout;
        import java.awt.Color;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.net.Socket;
        import java.net.UnknownHostException;
        import java.util.concurrent.atomic.AtomicInteger;
        import javax.swing.JButton;
        import javax.swing.JFrame;
        import javax.swing.JLabel;
        import javax.swing.JMenu;
        import javax.swing.JMenuBar;
        import javax.swing.JMenuItem;
        import javax.swing.JOptionPane;
        import javax.swing.JPanel;
        import javax.swing.JPasswordField;
        import javax.swing.SwingUtilities;
        import javax.swing.SwingWorker;
        import javax.swing.text.AttributeSet;
        import javax.swing.text.BadLocationException;
        import javax.swing.text.DocumentFilter;
        import javax.swing.text.PlainDocument;
     
        public class Client extends JFrame {
     
     
     
        	private static final long serialVersionUID = 1L;
     
        	private JPanel container = new JPanel();
        	private JPasswordField p1 = new JPasswordField(4);
        	private JLabel label = new JLabel("Enter Pin: ");
        	private JButton b = new JButton("OK");
     
     
        	public Client() {
        		this.setTitle("NEEDS");
        		this.setSize(300, 500);
        		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        		this.setLocationRelativeTo(null);
     
        		container.setBackground(Color.white);
        		container.setLayout(new BorderLayout());
        		container.add(p1);
        		JPanel top = new JPanel();
     
        		PlainDocument document =(PlainDocument)p1.getDocument();
     
        		p1.addActionListener(new ActionListener() {
        		    public void actionPerformed(ActionEvent evt) {
        		        b.doClick(); // Re-use the Ok buttons ActionListener...
        		    }
        		});
     
        		b.addActionListener(new BoutonListener());
     
        		top.add(label);
        		top.add(p1);
        		p1.setEchoChar('*');
        		top.add(b);
     
     
        		document.setDocumentFilter(new DocumentFilter(){
     
                    @Override
                    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                        String string =fb.getDocument().getText(0, fb.getDocument().getLength())+text;
     
                        if(string.length() <= 4)
                        super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates.
                    }
                });
     
                this.setContentPane(top);
        		this.setVisible(true);
        	}
     
        	class BoutonListener implements ActionListener {
        		private final AtomicInteger nbTry = new AtomicInteger(0);
        		//ArrayList<Integer> pins = readPinsData(new File("bdd.txt"));
     
        		@SuppressWarnings("deprecation")
        		public void actionPerformed(ActionEvent e) {
        			if (nbTry.get() > 2) {
        				JOptionPane.showMessageDialog(null,
        						"Pin blocked due to 3 wrong tries");
        				return;
        			}
        			final String passEntered = p1.getText().replaceAll("\u00A0", "");
        			if (passEntered.length() != 4) {
        				JOptionPane.showMessageDialog(null, "Pin must be 4 digits");
        				return;
        			}
     
        			SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        				@Override
        				protected Void doInBackground() throws Exception {
        //					boolean authenticated = false;
        //					final ImageIcon imgAngry = new ImageIcon("angry.png");
        //					final ImageIcon imgHappy = new ImageIcon("happy.png");
     
        //					if (pins.contains(Integer.parseInt(passEntered))) {
        //						JOptionPane.showMessageDialog(null, "Pin correct", "Good Pin", JOptionPane.INFORMATION_MESSAGE, imgHappy);
        //                        authenticated = true;
        //                    }
        //
        //                    if (!authenticated) {
        //                    	JOptionPane.showMessageDialog(null, "Wrong Pin", "Wrong Pin", JOptionPane.INFORMATION_MESSAGE, imgAngry);
        //                        nbTry.incrementAndGet();
        //                    }
                            return null;
        				}
        			};
        			worker.execute();
        		}
     
     
     
        	}
     
        	public static void main(String[] args) {
     
        		Socket socket;
        		BufferedReader in;
     
        		try {
     
        			socket = new Socket("192.168.217.128",2009);	
        			JOptionPane.showMessageDialog(null,"Asking for connection");
     
        		        in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
        		        String message_distant = in.readLine();
        		        System.out.println(message_distant);
     
                            SwingUtilities.invokeLater(new Runnable() {
            			@Override
            			public void run() {
            				new Client();
            			}
            		});
     
        		        socket.close();
     
        		}catch (UnknownHostException e) {
     
        			e.printStackTrace();
        		}catch (IOException e) {
     
        			e.printStackTrace();
        		}
     
        	}
        }

    Et voici Server.java (dans le même dossier que bdd.txt) :

    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
    import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.net.ServerSocket;
        import java.net.Socket;
        import java.io.File;
        import java.io.FileReader;
        import java.util.ArrayList;
     
        import javax.swing.JOptionPane;
     
        public class Server {
     
        	public static ArrayList<Integer> readPinsData(File dataFile) {
                final ArrayList<Integer> data = new ArrayList<Integer>();
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(dataFile));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            try {
                                data.add(Integer.parseInt(line));
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                                System.err.printf("error parsing line '%s'\n", line);
                            }
                        }
                    } finally {
                        reader.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("error:" + e.getMessage());
                }
     
                return data;
            }
     
        	public static void main(String[] args) {
     
                ServerSocket socketserver  ;
                Socket socketduserveur ;
                PrintWriter out;
     
                try {
     
                    socketserver = new ServerSocket(2009);
                    JOptionPane.showMessageDialog(null,"Server listening on port "+socketserver.getLocalPort());
                    socketduserveur = socketserver.accept(); 
                    out = new PrintWriter(socketduserveur.getOutputStream());
     
                        out.flush();
     
                        socketduserveur.close();
                        socketserver.close();
     
                }catch (IOException e) {
     
                    e.printStackTrace();
                }
     
        	}
        }

  2. #2
    Membre éprouvé
    Profil pro
    Inscrit en
    Février 2010
    Messages
    765
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 765
    Points : 1 036
    Points
    1 036
    Par défaut
    Bonjour,

    Le serveur accept la connection mais effectivement tu ne lis jamais rien ...

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2012
    Messages : 13
    Points : 10
    Points
    10
    Par défaut
    Une petite idée de pourquoi?

  4. #4
    Membre expérimenté Avatar de Nico02
    Homme Profil pro
    Developpeur Java/JEE
    Inscrit en
    Février 2011
    Messages
    728
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Developpeur Java/JEE
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2011
    Messages : 728
    Points : 1 622
    Points
    1 622
    Par défaut
    Citation Envoyé par flo2708 Voir le message
    Une petite idée de pourquoi?
    Au hasard je dirais que c'est parce que tu n'as pas écris le code pour le faire

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    socketduserveur = socketserver.accept(); 
    out = new PrintWriter(socketduserveur.getOutputStream());
    out.flush();
    socketduserveur.close();
    socketserver.close();
    Ici la méthode accept() attends une connexion, et dès qu'il y en a une tu fais un flush() (ce qui n'a aucun sens puisque tu n'as rien écrit dans le flux) et puis bah le programme se termine tout simplement.

    Il n'y a aucun appel à ta méthode readPinsData() coté serveur.

Discussions similaires

  1. Comment sauvegarder un fichier dans une table sqlite?
    Par Hamdi Hedhili dans le forum SQLite
    Réponses: 2
    Dernier message: 13/11/2008, 09h28
  2. [PostgreSQL] [PostGreSQL] Comment uploader un fichier dans une champ binaire ?
    Par Ekimasu dans le forum PHP & Base de données
    Réponses: 3
    Dernier message: 13/06/2008, 15h39
  3. Réponses: 3
    Dernier message: 09/06/2008, 15h01
  4. Comment décompresser un fichier dans une application ?
    Par f6dqm1 dans le forum Composants VCL
    Réponses: 8
    Dernier message: 14/01/2005, 16h31

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