B4R Tutorial [B4X] B4RSerializator - Send and receive objects instead of bytes

Status
Not open for further replies.
B4R v1.50 includes a new type named B4RSerializator (in rRandomAccessFile library).
B4RSerializator solves a difficult and common task. Sending messages with multiple fields to other platforms.

B4RSerializator takes an array of objects with numbers, strings and arrays of bytes and returns an array of bytes.

You can then send the array of bytes to other B4A, B4i, B4J or B4R applications and use the attached B4RSerializator class to decode the array of bytes back to an array of objects.

It works both ways. You can convert the array of bytes in the B4A, B4i or B4J application and convert it back to an array of objects in the B4R application (or in any other platforms).

Differences between B4RSerializator and B4XSerializator

B4XSerializator is supported by B4A, B4i and B4J. B4RSerializator is supported by all 4 tools.
B4XSerializator is more powerful and supports more types including complex types. B4RSerializator supports numbers, strings and arrays of bytes. Note that booleans are converted to 0 or 1.

B4RSerializator is more lightweight and produces more compact output (optimized for smaller messages).

Usage

It is very simple to use B4RSerializator.
Example:
B4X:
'ser is a B4RSerializator object
'sending side
astream.Write(ser.ConvertArrayToBytes(Array("Sent from B4A", DateTime.Time(DateTime.Now), 1000)))

'receiving side
Sub Astream_NewData (Buffer() As Byte)
Dim data() As Object = ser.ConvertBytesToArray(Buffer)
If data.Length = 0 Then Return 'invalid message
Dim LuckyNumber As Int = data(2)
For Each o As Object In data
  Log(o)
Next
End Sub
Note that in B4R ConvertBytesToArray there is a second parameter:
B4X:
Dim be(10) As Object 'used as a storage buffer. Can be a global variable
Dim data() As Object = ser.ConvertBytesToArray(Buffer, be)
The storage buffer size must be equal or larger than the number of items in the message.


B4RSerializator class is attached (compatible with B4A, B4i and B4J).
B4R type is included in rRandomAccessFile library.

Example of socket connection between Android and ESP8266 is attached.
The B4R example depends on rRandomAccessFile v1.8+.
 

Attachments

  • B4RSerializator.bas
    4.9 KB · Views: 3,303
  • B4R_Server.zip
    1.1 KB · Views: 3,283
  • B4A_Client.zip
    10 KB · Views: 3,324
Last edited:

maleche

Active Member
Licensed User
Longtime User
Thank you!
Is b4r compatible with the encoder library?
The data are from string potentiometers.
 
Status
Not open for further replies.
Top