Bonjour,
Je dois faire une application client/serveur NIO qui s'envoi une requete et se la retransmet des qu'il recoive une réponse.

client: CONNECT
serveur:ACCEPT
serveur : READ <-
client :SEND ->
client :READ <-
serveur SEND ->
...

Sauf que problème (pour 3 envoi-réponses):
du coté serveur
----------Lancement serveur---------
Lecture...
numread 96 reçu: Client: 1 mes: Hello world! i= 1Client: 1 mes: Hello world! i= 3Client: 1 mes: Hello world! i= 5
envoi...
Réponse envoyée:Client: 1 mes: Hello world! i= 1Client: 1 mes: Hello world! i= 3Client: 1 mes: Hello world! i= 5
--------------------------------------
il les lit tous

et du coté client:
run:
* Iteration 0:connecté!
* Iteration 1:Envoi d'un ping
* Iteration 2:Lecture...
Résultat reçu:
-------------
* Iteration 3:Envoi d'un ping
* Iteration 4:Lecture...
Résultat reçu:
-------------
* Iteration 5:Envoi d'un ping
* Iteration 6:Lecture...
Résultat reçu:
-----------------------------------
Il ne lit rien et ne fait qu'envoyer.

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
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pingpong;
 
/**
 *
 * @author ***
 */
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Client implements Runnable {
 
    public static String request = "Hello world!";
    private SocketChannel socketChannel = null;
    private int lenght = 500;
    private ByteBuffer buffer = ByteBuffer.allocate(lenght);
        private ByteBuffer bufferSend;
    private int nbiteration = 0;
    private static int numClientTotal = 0;
    private int numClient;
    private int port = 5555;
    private int key = SelectionKey.OP_CONNECT;
    private int nbPingPong = 6;
 
    public static void main(String[] args) {
        new Thread(new Client()).start();
    }
 
    public Client() {
        numClientTotal++;
        numClient = numClientTotal;
        key = (SelectionKey.OP_CONNECT);
    }
 
    /**
     * procedure de connection
     *
     * @throws IOException
     */
    public void handleConnect() throws IOException {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(port));
 
        while (!socketChannel.finishConnect()) {
            // pretend to do something useful here
            System.out.println("Connection...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println("problème  de connection");
                e.printStackTrace();
            }
        }
        System.out.println("connecté!");
        key = (SelectionKey.OP_WRITE);
    }
 
    /**
     * Envoi d'une requete NIO
     */
    public void handleDataOut() {
        try {
            System.out.println("Envoi d'un ping");
            bufferSend = ByteBuffer.wrap(("Client: " + this.numClient + " mes: " + request + " i= " + this.nbiteration).getBytes());
            socketChannel.write(bufferSend);
            key = (SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * Ecoute de la réponse du serveur.
     */
    private void handleDataIn() {
        try {
            System.out.println("Lecture...");
            buffer.clear();                         //on vide le buffer.
            socketChannel.read(buffer);
            buffer.flip();                          //le pointeur du buffer à 0.
            System.out.println("Résultat reçu:" + new String(buffer.array()));
            key = (SelectionKey.OP_WRITE);
 
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    @Override
    public void run() {
        for (nbiteration = 0; nbiteration <= nbPingPong; nbiteration++) {
            try {
                System.out.print("* Iteration " + nbiteration + ":");
                //handle the event
                if (key == SelectionKey.OP_CONNECT) {
                    this.handleConnect();
                } else if (key == SelectionKey.OP_READ) {
                    handleDataIn();
                    System.out.println("-------------");
                } else if (key == SelectionKey.OP_WRITE) {
                    handleDataOut();
                }
 
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            this.socketChannel.close();
        } catch (IOException ex) {
            System.out.println("ECHEC close");
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
et le 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
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
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pingpong;
 
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 *
 * @author ***
 */
public class Server implements Runnable {
 
    private ServerSocketChannel disneyChannel;
    private InetAddress address;
    private int leHavre;
    private Selector raymondDomenech;
    private int lenght = 500;
    private ByteBuffer buffer = ByteBuffer.allocate(lenght);
 
    public Server(InetAddress host, int port) throws IOException {
        this.address = host;
        this.leHavre = port;
        this.raymondDomenech = SelectorProvider.provider().openSelector();
        // non blocking server
        disneyChannel = ServerSocketChannel.open();
        disneyChannel.configureBlocking(false);
        disneyChannel.socket().bind(new InetSocketAddress(address, port));
 
        // be notified when connection
        disneyChannel.register(raymondDomenech, SelectionKey.OP_ACCEPT);
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            new Thread(new Server(null, 5555)).start();
            System.out.println("----------Lancement serveur---------");
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Erreur Thread!");
        }
 
    }
 
    @Override
    public void run() {
        while (true) {
            try {
                this.raymondDomenech.select();
                Iterator selectedKeys = this.raymondDomenech.selectedKeys().iterator();
                while (selectedKeys.hasNext()) {
                    SelectionKey key = (SelectionKey) selectedKeys.next();
                    selectedKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    //handle the event
                    if (key.isAcceptable()) {
                        handleAccept(key);
                    } else if (key.isReadable()) {
                        handleDataIn(key);
                    } else if (key.isWritable()) {
                        handleDataOut(key);
                    }
                }
            } catch (IOException ex) {
                System.out.println("ERREUR RUN");
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 
    /**
     * Cas acceptation de connection
     *
     * @param key
     * @throws IOException
     */
    private void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        //accept la connection
        SocketChannel socketChannel = serverSocketChannel.accept();
        Socket socket = socketChannel.socket();
        socketChannel.configureBlocking(false);
 
        //Register
        socketChannel.register(raymondDomenech, SelectionKey.OP_READ);
    }
 
    /**
     * Cas de reception de data
     *
     * @param key
     * @throws IOException
     */
    private void handleDataIn(SelectionKey key) {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        int numRead = 0;
 
        try {
            buffer.clear();
            System.out.println("Lecture...");
            numRead = socketChannel.read(buffer);
            buffer.flip();
 
        } catch (IOException ex) {
            System.out.println("ECHEC DATAIN");
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            key.cancel();
            try {
                socketChannel.close();
            } catch (IOException ex1) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex1);
            }
            return;
        }
 
        if (numRead == -1) {
            try {
                key.channel().close();
                key.cancel();
            } catch (IOException ex) {
                                System.out.println("ERREUR NUMREAD");
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
            return;
        }
        this.processData(this, socketChannel, this.buffer.array(), numRead);
    }
 
    /**
     * Cas envoi de data;
     *
     * @param key
     * @throws IOException
     */
    private void handleDataOut(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            System.out.println("envoi...");
            socketChannel.write(buffer);
            System.out.println("Réponse envoyée:" + new String(buffer.array()));
            System.out.println("-----------------");
            buffer.clear();
            //mise en position d'écoute du channel.
            key.interestOps(SelectionKey.OP_READ);
                        buffer.rewind();
        } catch (IOException ex) {
            System.out.println("erreurDATAOUT");
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            key.cancel();
            socketChannel.close();
        }
    }
 
    /**
     * Traitement du data
     *
     * @param server
     * @param socketChannel
     * @param data
     * @param numRead
     */
    private void processData(Server server, SocketChannel socketChannel, byte[] data, int numRead) {
        String st = new String(data);
        System.out.println("numread " + numRead + " reçu: " + st);
        try {
            send(socketChannel, data);
 
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Echec processDATA." + numRead);
        }
    }
 
    /**
     * Envoi sur channel par octets.
     *
     * @param socketChannel
     * @param data
     */
    private void send(SocketChannel socketChannel, byte[] data) throws IOException {
        SelectionKey key = socketChannel.keyFor(raymondDomenech);
        key.interestOps(SelectionKey.OP_WRITE);
        buffer = ByteBuffer.wrap(data);
    }
}
c'est un peu long mais là je suis bien bloqué et rien de ce que je trouve comme ressource sur le net est pertinent vis à vis de mon pb.

merci à ceux qui auront suffisamment de courage pour trouver mon erreur :p