Ciao! Una parte della mia app contiene un socket tcp/ip. questo socket deve connettersi in remoto ad un serve e scambiare dei dati. L'invio dei dati funziona, ma la ricezione mi da problemi. Il socket è contenuto in un thread ed ho bisogno che la ricezione non sia di tipo "bloccante". Ho provato con questo cercando un po' in rete:
1
2ByteBuffer incomingLengthInBytes = ByteBuffer.allocate(4); // size of an 'int'
3
4socketChannel.read(incomingLengthInBytes);
5
6incomingLengthInBytes.rewind();
7
8int incomingLength = incomingLengthInBytes.getInt();
9
10if (incomingLength > 0)
11{
12inviaToast("Got Incoming Length as: " + incomingLength + " bytes");
13
14// now allocate the correct size for the message...
15ByteBuffer incomingData = ByteBuffer.allocate(incomingLength);
16
17socketChannel.read(incomingData);
18
19incomingData.rewind();
20
21incomingData.get(bustaRicevuta.pacchetto);
22bustaRicevuta.lenPacchetto = incomingLength;
23}
24
Il socket non è bloccante e tutto sembra funzionare, ma quando arrivano effettivamente dei dati, la variabile incomingLenght contiene un numero da fantascienza invece che la vera quantità di dati nel socket...
Qualche suggerimento? Alternative per un metodo non bloccante che funzioni? Bye bye![]()