Reading in Random data via Astreams

Comalco

Member
Licensed User
Longtime User
I am working my way through learning B4A and I am attempting some simple network comms. I have an embedded device sending random packets of hexadecimal data at intermittent periods varying from around 1-to-5 seconds apart - using TCPIP (not UDP).

I have tried to rework the AStreams example (below), but havent been able to get a NewConnection event to fire. I would have expected the new connection event to fire as soon as data is detected,

I know the data is being sent, and I know my IP address and the IP and port addresses of the device sending the data. I suspect I am doing something wrong, but if someone could assist it would be appreciated. The packets I am trying to receive are either 23 bytes or 1623 bytes in length and are hexadecimal - not text.

I am not using the prefix statement in Astreams.initialize as the packets can vary in length (but around the around the 23 or 1622 lengths). Maybe this is the source of my problems? Both packets end with an ETX ETX (2 bytes).

Any pointers for this newbie (or alternate code or method) appreciated!!


Sub Process_Globals
Dim AStreams As AsyncStreams
Dim Server As ServerSocket
Dim Socket1 As Socket
End Sub

Sub Globals
Dim EditText1 As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then Server.Initialize(2222, "Server")
Server.Listen
End If
' EditText1.Initialize("EditText1")
' EditText1.ForceDoneButton = True
' Activity.AddView(EditText1, 10dip, 10dip, 300dip, 60dip)
End Sub

Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)
If Successful Then
' ToastMessageShow("Connected", False)
Socket1 = NewSocket
AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")
Else
ToastMessageShow(LastException.Message, True)
End If
Server.Listen
End Sub

Sub AStreams_NewData (Buffer() As Byte)
Dim msg As String
msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
ToastMessageShow(msg, False)
Log(msg)
End Sub

Sub AStreams_Error
ToastMessageShow(LastException.Message, True)
End Sub

'press on the Done button to send textSub
EditText1_EnterPressed
' If AStreams.IsInitialized = False Then Return
' If EditText1.Text.Length > 0 Then
' Dim buffer() As Byte
' buffer = EditText1.Text.GetBytes("UTF8")
' AStreams.Write(buffer)
' EditText1.SelectAll
' Log("Sending: " & EditText1.Text)
' End If
End Sub

Sub Activity_Pause(UserClosed As Boolean)
If UserClosed Then Log("closing")
AStreams.Close
Socket1.Close
End If
End Sub
 

Comalco

Member
Licensed User
Longtime User
Thanks

My fault ...when I cut'n'pasted this code into my post I didnt have this moved to the next line. it is in my code and compiles OK. Thanks Erel
 
Upvote 0
Top