The AsyncStreams object allows you to read from an InputStream and write to an OutputStream in the background without blocking the main thread. See the AsyncStreams Tutorial. NewData event is raised when new data is available. Error event is raised when an error was encountered. You should check LastException to find the error. Terminated event is raised when the other side has terminated the connection. NewStream event is only raised in prefix mode when the other side sends a stream with WriteStream. This event is raised after the complete stream was received successfully. The event includes the saved stream folder and name. Note that the file name is an arbitrary string.
Events:
NewData (Buffer() As Byte) Error Terminated NewStream (Dir As String, FileName As String)
Initializes the object. Unlike in prefix mode, the NewData event will be raised with new data as soon as it is available. In - The InputStream that will be read. Pass Null if you only want to write with this object. Out - The OutputStream that is used for writing the data. Pass Null if you only want to read with this object. EventName - Determines the Subs that handle the NewData and Error events.
Initializes the object and sets it in "prefix" mode. In this mode incoming data should adhere to the following protocol: Every message begins with the message length as an Int value (4 bytes). This length should not include the additional 4 bytes. The NewData event will be raised only with full messages (not including the 4 bytes length value). The prefix Int value will be added to the output messages automatically. This makes it easier as you do not need to deal with broken messages. In - The InputStream that will be read. Pass Null if you only want to write with this object. BigEndian - Whether the length value is encoded in BigEndian or LittleEndian. Out - The OutputStream that is used for writing the data. Pass Null if you only want to read with this object. EventName - Determines the Subs that handle the NewData and Error events.
IsInitializedAsBoolean
Tests whether this object has been initialized.
OutputQueueSizeAsInt [read only]
Returns the number of messages waiting in the output queue.
SendAllAndCloseAsBoolean
Sends a message to the internal queue. AsyncStreams will be closed when the message is processed. The Terminated event will be raised. Returns False if the queue is full or the connection is not open.
StreamFolderAsString
Received streams will be saved in this folder.
StreamReceivedAsLong [read only]
Returns the number of bytes of the currently received file. Only valid in prefix mode.
StreamTotalAsLong [read only]
Returns the total number of bytes of the currently received file. Only valid in prefix mode.
Write (Buffer() AsByte) AsBoolean
Adds the given bytes array to the output stream queue. If the object was initialized with InitializePrefix then the array length will be added before the array. Returns False if the queue is full and it is not possible to queue the data.
Adds the given bytes array to the output stream queue. If the object was initialized with InitializePrefix then the array length will be added before the array. Returns False if the queue is full and it is not possible to queue the data.
Writes the given stream. This method is only supported in prefix mode. The checksum will be calculated and sent to the other size. The NewStream event will be raised, in the receiving side, after the stream was received successfully. This method is more efficient than sending the same data in chunks. It can handle streams of any size. In - InputStream that will be read. Note that the InputStream will be closed after the stream is sent. Size - Number of bytes to read from the stream.
Asynchronously converts the bytes to object. The BytesToObject event will be raised when the object is ready. Do not reuse the same B4XSerializator instance when calling asynchronous methods.
ConvertObjectToBytes (ObjectAsObject) AsByte()
In-memory version of RandomAccessFile.WriteB4XObject. The following types are supported: Lists, Arrays of bytes and Arrays of objects, Maps, Strings, primitive types and user defined types. Note that user defined types should be declared in the Main module.
Asynchronously converts the object to bytes. The ObjectToBytes event will be raised with the serialized bytes. Do not reuse the same B4XSerializator instance when calling asynchronous methods.
TagAsObject
Gets or sets the Tag value. This is a place holder that can used to store additional data.
CompressedStreams object allows you to compress and decompress data using gzip or zlib compression methods. There are two options for working with CompressedStreams: Wrapping another stream by calling WrapInputStream or WrapOutputStream. Compressing or decompressing the data in memory. The following example demonstrates the usage of this object: SubGlobals
EndSub
SubActivity_Create(FirstTimeAsBoolean)
DimsbAsStringBuilder sb.Initialize 'Concatenation operations are much faster with StringBuilder than with String. Fori = 1To10000 sb.Append("Playing with compressed streams.").Append(CRLF)
Next DimoutAsOutputStream DimsAsString DimcompressAsCompressedStreams s = sb.ToString 'Write the string without compressing it (we could have used File.WriteString instead). out = File.OpenOutput(File.DirRootExternal, "test.txt", False)
WriteStringToStream(out, s)
'Write the string with gzip compression. out = File.OpenOutput(File.DirRootExternal, "test.gz", False)
out = compress.WrapOutputStream(out, "gzip")
WriteStringToStream(out, s)
'Write the string with zlib compression out = File.OpenOutput(File.DirRootExternal, "test.zlib", False)
out = compress.WrapOutputStream(out, "zlib")
WriteStringToStream(out, s)
'Read data from a compressed file DiminAsInputStream in = File.OpenInput(File.DirRootExternal, "test.zlib")
in = compress.WrapInputStream(in, "zlib")
DimreaderAsTextReader reader.Initialize(in)
DimlineAsString line = reader.ReadLine Msgbox(line, "First line")
reader.Close
'In memory compression / decompression Dimdata() AsByte data = "Playing with in-memory compression.".GetBytes("UTF8")
Dimcompressed(), decompressed() AsByte compressed = compress.CompressBytes(data, "gzip")
decompressed = compress.DecompressBytes(compressed, "gzip")
'In this case the compressed data is longer than the decompressed data. 'The data is too short for the compression to be useful. Log("Compressed: " & compressed.Length)
Log("Decompressed: " & decompressed.Length)
Msgbox(BytesToString(decompressed,0, decompressed.Length, "UTF8"), "")
EndSub SubWriteStringToStream(OutAsOutputStream, sAsString)
DimtAsTextWriter t.Initialize(Out)
t.Write(s)
t.Close'Closes the internal stream as well EndSub
Returns a byte array with the decompressed data. CompressedData - The compressed data that should be decompressed. CompressMethod - The name of the compression method (gzip or zlib).
Wraps an input stream and returns an input stream that automatically decompresses the stream when it is read. In - The original input stream. CompressMethod - The name of the compression method (gzip or zlib).
Wraps an output streams and returns an output stream that automatically compresses the data when it is written to the stream. Out - The original output stream. CompressMethod - The name of the compression method (gzip or zlib).
CountingInputStream and CountingOutputStream allow you to monitor the reading or writing progress. Counting streams wrap the actual stream and provide a Count property which allows you to get the number of bytes read or written. Counting streams are useful when the reading or writing operations are done in the background. You can then use a timer to monitor the progress. This example logs the downloading progress: SubProcess_Globals DimhcAsHttpClient DimcoutAsCountingOutputStream DimlengthAsInt Dimtimer1AsTimer EndSub SubGlobals
This object allows you to non-sequentially access files and bytes arrays. You can also use it to encode numbers to bytes (and vice versa). Note that assets files (files added with the file manager) cannot be opened with this object as those files are actually packed inside the APK file. A short tutorial about the encryption methods is available here.
Opens the specified file. Note that it is not possible to open a file saved in the assets folder with this object. If needed you can copy the file to another location and then open it. ReadOnly - Whether to open the file in read only mode (otherwise it will be readable and writable). Example: DimrafAsRandomAccessFile raf.Initialize(File.DirInternal, "1.dat", false)
Same as Initialize with the option to set the byte order to little endian instead of the default big endian. This can be useful when sharing files with Windows computers.
Reads bytes from the stream and into to the given array. Buffer - Array of bytes where the data will be written to. StartOffset - The first byte read will be written to Buffer(StartOffset). Length - Number of bytes to read. Position - The position of the first byte to read. Returns the number of bytes read which is equal to Length (unless the file is smaller than the requested length).
ReadDouble (PositionAsLong) AsDouble
Reads a Double value stored in the specified position. Reads 8 bytes.
Reads an encrypted object from the stream. Password - The password used while writing the object. Position - Stream position.
ReadFloat (PositionAsLong) AsFloat
Reads a Float value stored in the specified position. Reads 4 bytes.
ReadInt (PositionAsLong) AsInt
Reads an Int value stored in the specified position. Reads 4 bytes.
ReadLong (PositionAsLong) AsLong
Reads a Long value stored in the specified position. Reads 8 bytes.
ReadObject (PositionAsLong) AsObject
Reads an object from the stream. See WriteObject for supported types.
ReadShort (PositionAsLong) AsShort
Reads a Short value stored in the specified position. Reads 2 bytes.
ReadSignedByte (PositionAsLong) AsByte
Reads a signed byte (-128 - 127) stored in the specified position.
ReadUnsignedByte (PositionAsLong) AsInt
Reads an unsigned bytes (0 - 255) stored in the specified position. The value returned is of type Int as Byte can only store values between -128 to 127.
SizeAsLong [read only]
Returns the file size.
WriteB4XObject (ObjectAsObject, PositionAsLong)
Similar to WriteObject. This method writes the object in a format supported by B4i, B4A and B4J. The following types are supported: Lists, Arrays of bytes and Arrays of objects, Maps, Strings, primitive types and user defined types. Note that user defined types should be declared in the Main module.
WriteByte (ByteAsByte, PositionAsLong)
Writes a Byte value to the specified position. Writes 1 byte.
Writes the given buffer to the stream. The first byte written is Buffer(StartOffset) and the last is Buffer(StartOffset + Length - 1). Returns the numbers of bytes written which is equal to Length.
WriteDouble (ValueAsDouble, PositionAsLong)
Writes a Double value to the specified position. Writes 8 bytes.
Similar to WriteObject. The object is encrypted with AES-256 and then written to the stream. Note that it is faster to write a single large object compared to many smaller objects. Object - The object that will be written. Password - The password that protects the object. Position - The position in the file that this object will be written to.
WriteFloat (ValueAsFloat, PositionAsLong)
Writes a Float value to the specified position. Writes 4 bytes.
WriteInt (ValueAsInt, PositionAsLong)
Writes an Int value to the specified position. Writes 4 bytes.
WriteLong (ValueAsLong, PositionAsLong)
Writes a Long value to the specified position. Writes 8 bytes.
Writes the given object to the stream. This method is capable of writing the following types of objects: Lists, Arrays, Maps, Strings, primitive types and user defined types. Combinations of these types are also supported. For example, a map with several lists of arrays can be written. The element type inside a collection must be a String or primitive type. Note that changing your package name may make older objects files unusable (requiring you to write them again). Object - The object that will be written. Compress - Whether to compress the data before writing it. Should be true in most cases. Position - The position in the file that this object will be written to.
WriteShort (ValueAsShort, PositionAsLong)
Writes a Short value to the specified position. Writes 2 bytes.
Top