Best way to transmit files to server? / Memory Issue

Silentsea

Member
Licensed User
Longtime User
Hi,

we connect our webserver trough a tcp socket, so far so good. Transmitting Database Data runs very well.

We put the image to an byte array first, then we encode this array to string of base64, this string we add to a queue list. By a timer we went trough this list like a stack we take the first item change this to send it to server as byte array.

Now our problem ist, that if we want to transmit large files, e.g. pictures of 1.5 Mb, the allocation of mem raises a oom error.

Is there a better way to transmit these files?

Here a code example:

B4X:
Sub Activity_Create(FirstTime As Boolean)

   Dim image() As Byte
   image = ImageToByte(File.DirRootExternal, "Filename.png")
               
   Dim b64 As Base64
   b64.EncodeBtoS(image,0, image.Length))
   
   stcp.Queue.Add(b64.EncodeBtoS(image,0, image.Length)))   
End Sub


' Open an image file and convert it to a byte array
Sub ImageToByte(Directory As String, FileName As String) As Byte()
   Try
      ' Open image file
      Dim in As InputStream
      in = File.OpenInput(Directory, FileName)
            
      ' Copy image file to bytes array
      Dim Out As OutputStream
      Out.InitializeToBytesArray(1024)
      
      File.Copy2(in, Out)
      
      Return Out.ToBytesArray
   Catch
      Log("ImagetoByte:" & LastException.Message)
   End Try
End Sub


'#############################
'##Code in service module stcp

' Periodicly check if there is a job in the Queue
Sub Interval_Tick
   ' If there are jobs in Queue, 
   ' handle one of them each Tick
   ' Otherwise exit
   If Queue.Size = 0 Then Return
   
   Try
      Out(Queue.Get(0))
      
      ' Remove job from Queue
      Queue.RemoveAt(0)

   Catch 
      cTools.debug(LastException.Message)      
   End Try
End Sub

' Prepare String and send it to the server
Sub Out (message As String)
   Try
      ' Convert String into byte array
      Dim messageBytes() As Byte
      Dim bc As ByteConverter 
      messageBytes = bc.StringToBytes(message, "UTF8")
      
      ' Send message to server
      OutBytes(messageBytes)
   Catch
      cTools.Debug("sTCP Out: " & LastException)
   End Try
End Sub

' Try to send byte array to server
Sub OutBytes (ByteArray() As Byte)
   ' Try to send message to server
   If AStream.IsInitialized Then
      Try
         AStream.Write(ByteArray)
      Catch
         Log(LastException.Message)
      End Try
   End If   
End Sub

Please advise

Regards Silentsea
 
Top