bonjour à tous
Voila je cherche a comprendre un sample de la msdn concernant l'utilisation du port série (framework 2) et je m'interesse tout particulièrement à la lecture.
Bon je vous ponds le code même si je sais que c'est un peu long
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
| private void Receive()
{
try
{
byte[] receiveBuffer = new byte[128];
int bytesRead = 0;
int bufferIndex = 0;
int startPacketIndex = 0;
int expectedPacketLength = -1;
bool expectedPacketLengthIsSet = false;
int numBytesToRead = receiveBuffer.Length;
while (true)
{
if (expectedPacketLengthIsSet || 1 >= bytesRead)
{
//If the expectedPacketLength has been or no bytes have been read
//This covers the case that more then 1 entire packet has been read in at a time
// comPort
try
{
bytesRead += com.Read(receiveBuffer, bufferIndex, numBytesToRead);
bufferIndex = startPacketIndex + bytesRead;
}
catch (TimeoutException)
{
_timedOut = true;
}
}
if (1 < bytesRead)
{
//The buffer has the dataLength for the packet
if (!expectedPacketLengthIsSet)
{
//If the expectedPacketLength has not been set for this packet
expectedPacketLength = receiveBuffer[(1 + startPacketIndex) % receiveBuffer.Length] + 4;
expectedPacketLengthIsSet = true;
}
if (bytesRead >= expectedPacketLength)
{
//The buffer has atleast as many bytes for this packet
AddPacket(receiveBuffer, startPacketIndex);
expectedPacketLengthIsSet = false;
if (bytesRead == expectedPacketLength)
{
//The buffer contains only the bytes for this packet
bytesRead = 0;
bufferIndex = startPacketIndex;
}
else
{
//The buffer also has bytes for the next packet
startPacketIndex += expectedPacketLength;
startPacketIndex %= receiveBuffer.Length;
bytesRead -= expectedPacketLength;
bufferIndex = startPacketIndex + bytesRead;
}
}
}
bufferIndex %= receiveBuffer.Length;
numBytesToRead = bufferIndex < startPacketIndex ? startPacketIndex - bufferIndex : receiveBuffer.Length - bufferIndex;
}
}
catch (IOException)
{
// abort the thread
System.Threading.Thread.CurrentThread.Abort();
}
catch (ObjectDisposedException)
{
if (receiveThread != null)
{
receiveThread = null;
}
}
} |
Je ne comprend pas grand chose a ce code je doit bien l'avouer mais j'espère que la question suivante va me debloquer quelque peu...
Quel est le sens du caractère % dans la ligne suivante par exemple ?
expectedPacketLength = receiveBuffer[(1 + startPacketIndex) % receiveBuffer.Length] + 4;
merci d'avance pour vos lumières
Partager