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 :

[socket] probleme lecture


Sujet :

Entrée/Sortie Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Rédacteur/Modérateur

    Avatar de gorgonite
    Homme Profil pro
    Ingénieur d'études
    Inscrit en
    Décembre 2005
    Messages
    10 322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur d'études
    Secteur : Transports

    Informations forums :
    Inscription : Décembre 2005
    Messages : 10 322
    Par défaut [socket] probleme lecture
    Salut,


    Je n'arrive pas à lire ce qui arrive dans ma socket...

    nb: je suis obligé de passer par les nio et les bytebuffer


    voilà ce que j'ai pour le moment
    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
    package tp01;
     
    import java.io.IOException;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.util.*;
     
     
    public class ServeurFTP {
    	public static int DEFAULT_PORT = 4000;
     
    	protected ServerSocketChannel serverChannel;
    	protected Selector selector;
     
    	public void openPort() {
    		try {
    			serverChannel = ServerSocketChannel.open();
    			ServerSocket ss = serverChannel.socket();
    			InetSocketAddress address = new InetSocketAddress(DEFAULT_PORT);
    			ss.bind(address);
    			serverChannel.configureBlocking(false);
    			selector = Selector.open();
    			serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    		} catch (IOException ex) {
    			ex.printStackTrace();
    			return;
    		}
    	}
     
    	protected void processIfAcceptable(SelectionKey key) {
    		try {		
    			ServerSocketChannel server = (ServerSocketChannel) key.channel();
    			SocketChannel client = server.accept();
    			System.out.println("Accepted connection from " + client);
    			client.configureBlocking(false);
    			SelectionKey clientKey = client.register( selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
    			ByteBuffer buffer = ByteBuffer.allocate(100);
    			clientKey.attach(buffer);
    		} catch (IOException ex) {
    			key.cancel();
    			try {
    				key.channel().close();
    			} catch (IOException cex) { }
    		}
    	}
     
    	protected ByteBuffer processIfReadable(SelectionKey key) {
    		try {			
    			SocketChannel client = (SocketChannel) key.channel();
    			ByteBuffer output = (ByteBuffer) key.attachment();
    			client.read(output);
    			return output;
    		} catch (IOException ex) {
    			key.cancel();
    			try {
    				key.channel().close();
    			} catch (IOException cex) { }
    			return (ByteBuffer) null;
    		}
    	}
     
    	public void startProcess() {
    		while (true) {
    			try {
    				selector.select();
    			} catch (IOException ex) {
    				ex.printStackTrace();
    				break;
    			}
     
    			Set readyKeys = selector.selectedKeys();
    			Iterator iterator = readyKeys.iterator();
    			while (iterator.hasNext()) {
    				SelectionKey key = (SelectionKey) iterator.next();
    				iterator.remove();
     
    				if (key.isAcceptable()) {
    					processIfAcceptable(key);
    				}
     
    				if (key.isReadable()) {
    					CharBuffer buf = processIfReadable(key).asCharBuffer();
    					System.out.println(buf.length() + " " + buf.capacity() + " " + buf.remaining());
    					buf.flip();
    					char[] tmp = new char[buf.length()];
    					buf.get(tmp);
    					String msg = new String(tmp);
     
    					if (msg.equals("")) {
    						System.out.println("string vide");
    						System.out.flush();
    					} else {
    						System.out.println(msg);
    						System.out.flush();						
    					}
    				}					
    			}
    		}		
    	}
     
    	public static void main(String[] args) {
    		ServeurFTP myServer = new ServeurFTP();
    		myServer.openPort();
    		myServer.startProcess();
    	}
    }

    si quelqu'un voit où j'ai faux... ça m'arrangerait beaucoup
    Evitez les MP pour les questions techniques... il y a des forums
    Contributions sur DVP : Mes Tutos | Mon Blog

  2. #2
    Rédacteur/Modérateur

    Avatar de gorgonite
    Homme Profil pro
    Ingénieur d'études
    Inscrit en
    Décembre 2005
    Messages
    10 322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur d'études
    Secteur : Transports

    Informations forums :
    Inscription : Décembre 2005
    Messages : 10 322
    Par défaut
    vraiment pas inspiré

    Evitez les MP pour les questions techniques... il y a des forums
    Contributions sur DVP : Mes Tutos | Mon Blog

  3. #3
    Rédacteur/Modérateur

    Avatar de gorgonite
    Homme Profil pro
    Ingénieur d'études
    Inscrit en
    Décembre 2005
    Messages
    10 322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur d'études
    Secteur : Transports

    Informations forums :
    Inscription : Décembre 2005
    Messages : 10 322
    Par défaut
    Citation Envoyé par gorgonite
    vraiment pas inspiré


    toujours pas... de mon côté, je reste toujours bloqué sur l'extraction du contenu du ByteBuffer en String
    Evitez les MP pour les questions techniques... il y a des forums
    Contributions sur DVP : Mes Tutos | Mon Blog

  4. #4
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 900
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 900
    Billets dans le blog
    54
    Par défaut
    Hello, j'avoue que je n'ai jamais utilise les nio sur les socket reseau, uniquement (et encore tres peu) sur des flux locaux.

    Sinon, new String(buffer.array()) ou buffer.toString() ne fonctionnent pas ?
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  5. #5
    Rédacteur/Modérateur

    Avatar de gorgonite
    Homme Profil pro
    Ingénieur d'études
    Inscrit en
    Décembre 2005
    Messages
    10 322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur d'études
    Secteur : Transports

    Informations forums :
    Inscription : Décembre 2005
    Messages : 10 322
    Par défaut
    nan ça ne veut pas...


    j'ai une solution, mais elle est moche
    je lis par blocs de 1 caractère et je concatène



    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
    package tp01;
     
    import java.io.*;
     
     
    public class ServeurFTP {
    	public static int DEFAULT_PORT = 4000;
     
    	protected ServerSocketChannel serverChannel;
    	protected Selector selector;
    	protected String pwd;
     
    	public ServeurFTP() {
    		refreshPWD(".");
    	}
     
    	public void refreshPWD(String str) {
    		String tempStr = (new File(str)).getAbsolutePath();
    		if (!tempStr.equals("/")) {
    			pwd = tempStr.substring(0, tempStr.length()-2);
    		}		
    	}
     
    	public void openPort() {
    		try {
    			serverChannel = ServerSocketChannel.open();
    			ServerSocket ss = serverChannel.socket();
    			InetSocketAddress address = new InetSocketAddress(DEFAULT_PORT);
    			ss.bind(address);
    			serverChannel.configureBlocking(false);
    			selector = Selector.open();
    			serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    		} catch (IOException ex) {
    			ex.printStackTrace();
    			return;
    		}
    	}
     
    	protected void processIfAcceptable(SelectionKey key) {
    		try {		
    			ServerSocketChannel server = (ServerSocketChannel) key.channel();
    			SocketChannel client = server.accept();
    			System.out.println("Accepted connection from " + client);
    			client.configureBlocking(false);
    			SelectionKey clientKey = client.register( selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
    			ByteBuffer buffer = ByteBuffer.allocate(100);
    			clientKey.attach(buffer);
    		} catch (IOException ex) {
    			key.cancel();
    			try {
    				key.channel().close();
    			} catch (IOException cex) { }
    		}
    	}
     
    	protected ReponseBuffer processIfReadable(SelectionKey key) {
    		try {			
    			SocketChannel client = (SocketChannel) key.channel();
    			ByteBuffer output = (ByteBuffer) key.attachment();
    			int len = client.read(output);
    			return new ReponseBuffer(len, output);
    		} catch (IOException ex) {
    			key.cancel();
    			try {
    				key.channel().close();
    			} catch (IOException cex) { }
    			return new ReponseBuffer(0, null);
    		}
    	}
     
    	protected void sendAnswer(SelectionKey key, String str) {
    		try {			
    			SocketChannel client = (SocketChannel) key.channel();
    			ByteBuffer output = ByteBuffer.wrap(str.getBytes());
    			client.write(output);
    		} catch (IOException ex) {
    			key.cancel();
    			try {
    				key.channel().close();
    			} catch (IOException cex) { }
    		}		
    	}
     
    	public void startProcess() {
    		while (true) {
    			try {
    				selector.select();
    			} catch (IOException ex) {
    				ex.printStackTrace();
    				break;
    			}
     
    			Set readyKeys = selector.selectedKeys();
    			Iterator iterator = readyKeys.iterator();
    			while (iterator.hasNext()) {
    				SelectionKey key = (SelectionKey) iterator.next();
    				iterator.remove();
     
    				if (key.isAcceptable()) {
    					processIfAcceptable(key);
    				}
     
    				if (key.isReadable()) {
    					ByteBuffer buf = processIfReadable(key).getBuf();
    					buf.flip();
    					byte[] tmp = new byte[1];
    					String temp = new String();
    					while (buf.hasRemaining()) {
    						buf.get(tmp);
    						temp += new String(tmp);
    					}
     
    					String msg;
    					if (temp.length() > 2) {
    						msg = temp.substring(0, temp.length()-2);
    					} else {
    						break;
    					}
    					System.out.println(msg.length() + "\t" + msg);
     
    					String answer = new String();
    					boolean hasSwitched = false;
     
    					if (msg.equals("bye")) {
    						key.cancel();
    					}
     
    					if (msg.equals("pwd")) {
    						hasSwitched = true;
    						answer = pwd;
     
    					}
     
    					if (msg.startsWith("cd")) {
    						hasSwitched = true;
    						String oldPwd = pwd;
     
    						int i = 2;
    						while (msg.charAt(i) == ' ') {
    							i++;
    						}
    						String mesg = msg.substring(i);
     
    						if (mesg.startsWith("..")) {
    							if (pwd != "/") {
    								int lastSlashAt = pwd.lastIndexOf("/");
    								pwd = pwd.substring(0, lastSlashAt);
     
    								int firstSlashAt = mesg.indexOf("/");
    								if (firstSlashAt != -1) {
    									pwd += "/" + mesg.substring(firstSlashAt+1);
    								}
    							}
    						} else {
    							pwd += "/" + mesg;
    						}
    						answer = "Nouveau répertoire de travail " + pwd;
     
    						if (!(new File(pwd)).exists()) {
    							answer = "Répertoire " + pwd + " inexistant";
    							pwd = oldPwd;
    						}
    					}
     
    					if (!hasSwitched) {
    							answer = "Commande inconnue";
    					}
     
    					if (key.isValid() && key.isWritable()) {
    						System.out.println(answer);						
    						sendAnswer(key, answer+"\n");
    					}
     
    					buf.clear();
    				}				
    			}
    		}		
    	}
     
    	public static void main(String[] args) {
    		ServeurFTP myServer = new ServeurFTP();
    		myServer.openPort();
    		try {
    			myServer.startProcess();
    		} catch (Exception ex) {
    			ex.printStackTrace();
    		}
    	}
    }

    j'ai tout mis pour que vous puissiez tester...
    Evitez les MP pour les questions techniques... il y a des forums
    Contributions sur DVP : Mes Tutos | Mon Blog

  6. #6
    Rédacteur/Modérateur

    Avatar de gorgonite
    Homme Profil pro
    Ingénieur d'études
    Inscrit en
    Décembre 2005
    Messages
    10 322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur d'études
    Secteur : Transports

    Informations forums :
    Inscription : Décembre 2005
    Messages : 10 322
    Par défaut
    vraiment personne ?
    Evitez les MP pour les questions techniques... il y a des forums
    Contributions sur DVP : Mes Tutos | Mon Blog

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

Discussions similaires

  1. probleme lecture/ecriture socket
    Par joubiyann dans le forum C#
    Réponses: 1
    Dernier message: 31/03/2009, 09h56
  2. probleme lecture dans un socket
    Par sneb5757 dans le forum Réseau
    Réponses: 8
    Dernier message: 02/12/2006, 16h40
  3. Probleme lecture fichier
    Par CaptainChoc dans le forum C++
    Réponses: 5
    Dernier message: 06/03/2005, 10h40
  4. [LG]probleme lecture fichier
    Par yp036871 dans le forum Langage
    Réponses: 2
    Dernier message: 28/01/2004, 19h22
  5. [LG]Probleme lecture fichier file of ....
    Par John_win dans le forum Langage
    Réponses: 11
    Dernier message: 11/11/2003, 18h53

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