static variables:
Dim CurrentSender As String = ""
Dim NumChunks As Int = 0 'non-zero = reception in progress
Dim ChunkBuffer As Map
Sub HandleImageMessage (Sender As String, Data() As Byte)
If Sender <> CurrentSender Then
CurrentSender = Sender
NumChunks = 0
End If
If NumChunks = 0 Then
Dim HighByte As Int = Bit.And(Data(6), 0xFF)
Dim LowByte As Int = Bit.And(Data(7), 0xFF)
Dim NumChunks = Bit.Or(Bit.ShiftLeft(HighByte, 8), LowByte) '16-bit chunk count from header
ChunkBuffer.Initialize
End if
Dim HighByte As Int = Bit.And(Data(4), 0xFF)
Dim LowByte As Int = Bit.And(Data(5), 0xFF)
Dim ThisChunkNumber = Bit.Or(Bit.ShiftLeft(HighByte, 8), LowByte) '16 bit current chunk number from header
ChunkBuffer.Put(ThisChunkNumber, Data()) 'header and all - will strip that off when we assemble full image
If ChunkBuffer.Size = NumChunks Then 'we have all chunks
'determine size of full image (not including headers)
Dim FullImageSize As Int = 0
For ChunkNumber = 1 to NumChunks
Dim B() As Byte = ChunkBuffer.Get(ChunkNumber)
FullImageSize = FullImageSize + B.Length - 12
Next
'allocate buffer for assembly of full image
Dim FullImage(FullImageSize) As Byte
'assemble image
Dim FullImageSizeSoFar As Int = 0
For ChunkNumber = 1 to NumChunks
Dim B() As Byte = ChunkBuffer.Get(ChunkNumber)
bc.ArrayCopy(B, 12, FullImage, FullImageSizeSoFar, B.Length - 12)
FullImageSizeSoFar = FullImageSizeSoFar + B.Length - 12
Next
NumChunks = 0 'prepare for next incoming
ImageBuffer.Initialize 'clear buffer
'pass to somebody who knows what to do with it...
ImageReceived(Sender, FullImage, FullImage.Length)
End If
End Sub