Trame reçue en plusieurs étapes
Bonjour,
Je suis entrain de faire un serveur socket avec API NIO, ma question est la suivante , comment je peux recevoir les messages (sous forme de string en Hexa) dans le cas où il y a des problèmes ou des surcharge coté réseau ce qui va entrainer que mes trames vont arrivé en plusieurs morceau ,sachant que je connais pas la taille du message envoyé par un client.
voici mon code utilisé jusqu’à maintenant :
Code:
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
|
while (active) {
try {
selector.select();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
try {
SelectionKey key = keys.next();
keys.remove();
if (!key.isValid()) {
continue;
}
//l'évenement correspond à une acceptation de connexion
if(key.isAcceptable()) {
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
System.out.println("Client is connected");
}
//l'évenement correspond à une lecture
else if(key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
doRead(client, key);
}
//l'évenement correspond à l'écriture
else if(key.isWritable()) {
SocketChannel client = (SocketChannel) key.channel();
doWrite(client, key);
}
} catch (IOException e) {
trace.println(-1, "Exception in channel", e);
if(keys != null)
keys.remove();
}
}
} catch (ClosedChannelException e) {
trace.println(-1, "Exception in closing channel", e);
} catch (IOException e) {
trace.println(-1, "Exception in channel", e);
}
} |
Code:
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
|
public void doRead(SocketChannel client , SelectionKey key) throws IOException {
ByteBuffer readBuffer = ByteBuffer.allocate(8192);
readBuffer.clear();
int numread ;
while (true) {
numread = client.read( readBuffer );
if (numread <=0) {
break;
}
}
if (numread == -1) {
return ;
}
readBuffer.flip() ;
System.out.println("SERVER RECEVE : " + new String(readBuffer.array())) ;
processCommunication(client , readBuffer);
key.interestOps(SelectionKey.OP_WRITE) ;
} |
Code:
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
|
public void doWrite(SocketChannel client , SelectionKey key) throws IOException {
//ByteBuffer resp = ByteBuffer.wrap(("ACK : "+message).getBytes());
ByteBuffer resp = queuedWrites.get(client) ;
System.out.println("SERVER RESPONSE :" + new String(resp.array())) ;
while (true) {
int n = client.write(resp) ;
if (n == 0 || resp.remaining() == 0)
break ;
}
key.interestOps(SelectionKey.OP_READ) ;
if("ACK".equalsIgnoreCase(new String(resp.array()).trim())) {
client.close();
key.channel().close();
key.cancel();
}
} |
J'ai lu sur le net , qu'il faut utiliser un objet attaché au Key , mais je sais pas comment faire cela pour résoudre mon problème :?
Merci d'avance ;)