Home
> Uncategorized > Packet fragmentation over the internet
Packet fragmentation over the internet
Somebody wrote to me telling me that the code I included in my book to send and receive files via TCP sometimes hangs.
You can improve the handling of files within the TCP file reciever program in two ways.
Firstly, instead of
"if (thisRead==0) break;"
it should be
"if (thisRead<=0) break;"
Furthermore, it is possible for packets of less than 1024 bytes to be sent at a time (this does not
happen over a local network, but sometimes happens over the internet). This could lead to file
corruption where packet-fragments are padded with zero’s in the output file.
So the code could be further improved thus:
System
.Collections.ArrayList al = new ArrayList(); byte[] RecvBytes = new byte[Byte.MaxValue]; Int32 bytes; Int32 totalLength=0while
(true){
bytes = networkStream.Read(RecvBytes, 0,RecvBytes.Length); if (bytes<=0) break; totalLength += bytes; al.AddRange(cropByteArray(RecvBytes,bytes)); }al
= al.GetRange(0,totalLength); networkStream.Close();byte
[] returnedData = (byte[])al.ToArray((new byte()).GetType()); OnFTPMessageEvent(Encoding.ASCII.GetString(returnedData));
and also define the function cropByteArray thus:
private
byte[] cropByteArray(byte[] inputArray, Int32 crop)
{
byte[] outputArray = new byte[crop];
for (int i=0;i<crop;i++)
{
outputArray[i]=inputArray[i];
}
return outputArray;
}
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback