B4A Library [class] AsyncStreamsText - Useful when working with streams of text

Status
Not open for further replies.
When a message (set of bytes) is sent over a network channel, of any type, there is no guarantee that the whole message will arrive as a single set of bytes.

The message might be split or merged together with other messages.

One way to overcome this issue is to initialize AsyncStreams in "prefix" mode. In this mode a 4 bytes header is added to each message with the message length. This allows AsyncStreams to internally build the messages correctly. However you can only use prefix mode if both sides of the connection adhere to this protocol. If for example you connect to a Bluetooth GPS then you cannot use prefix mode.

AsyncStreamsText can help you if:
1. The data sent is text and not binary data.
2. Each message ends with an end of line character (both Unix and Windows formats will work).

AsyncStreamsText works by handling the NewData event and looking for the end of line characters.

Using AsyncStreamsText is simple:
B4X:
Sub Process_Globals
   Private ast As AsyncStreamsText
   Private server As ServerSocket
End Sub

Sub Globals
End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      server.Initialize(5555, "server")
      Log(server.GetMyWifiIP)
      server.Listen
   End If
End Sub

Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)
   If Successful Then
      If ast.IsInitialized Then ast.Close
      ast.Initialize(Me, "ast", NewSocket.InputStream, NewSocket.OutputStream) 'initialize AsyncStreamsText with the socket streams.
   Else
      Log(LastException)
   End If
   server.Listen
End Sub

Sub ast_NewText(Text As String)
   Log("Text: " & Text)
   Log(Text.Length)
End Sub

Sub ast_Terminated
   Log("Connection terminated")
End Sub

Sub Activity_Click
   ast.Write("this is an example..." & Chr(10) & Chr(13))
End Sub

NewText event is raised each time that there is a complete message available.

Note that AsyncStreamsText.Write writes text and not bytes.
The charset field sets the encoding used to convert the bytes to string and vice versa.
 

Attachments

  • AsyncStreamsText.bas
    1.8 KB · Views: 3,208
Last edited:
D

Deleted member 103

Guest
Hallo , I changes the Astreams to AST,
If you are already changing the name, then you should also change the event name.
from:
B4X:
Sub AStreams_NewData (Buffer() As Byte)
to
B4X:
Sub AST_NewData (Buffer() As Byte)
 

DonManfred

Expert
Licensed User
Longtime User
If you are already changing the name, then you should also change the event name.
Wrong solution!

AStreamText uses String instead of bytes

B4X:
Sub ast_NewText(Text As String)
   Log("Text: " & Text)
   Log(Text.Length)
End Sub

Sub ast_Terminated
   Log("Connection terminated")
End Sub

Sub Activity_Click
   ast.Write("this is an example..." & Chr(10) & Chr(13))
End Sub
 
Status
Not open for further replies.
Top