Android Question Socket & AsyncStreams

luke2012

Well-Known Member
Licensed User
Longtime User
How to keep alive the socket connection ?
I mean that the user need to keep the app and the connection alive to send data to the connected devices.

B4X:
'STARTER

Sub Process_Globals
     Dim WFPrinter AsSocket 'Network library
     Dim AStreams AsAsyncStreams 'RandomAccessFile library
End Sub

'MAIN

Sub Activity_Resume
   Starter.WFPrinter.Initialize("WFPrinter")
   Starter.WFPrinter.Connect("192.168.0.87", 9100, 0)
End Sub

Sub Activity_Pause (UserClosed As Boolean)

If UserClosed Then
   Starter.AStreams.Close
   Starter.WFPrinter.Close
End If

End Sub

Sub WFPrinter_Connected (Successful As Boolean)

Log(Successful)

If Successful Then

Starter.AStreams.Initialize(Starter.WFPrinter.InputStream,       Starter.WFPrinter.OutputStream, "AStreams")

Else

End If

End Sub

I tested my code and I can see that the "AStreams_Terminated" is called also when the app is in foreground and KeepAlive(True) is called.
 

luke2012

Well-Known Member
Licensed User
Longtime User
You shouldn't initialize the variables from the main activity. Initialize them inside the service and manage all the communication related events in the service.

Example: [B4X] Network + AsyncStreams + B4XSerializator

I initialized the variables within the STARTER SERVICE but in the log I see the "AStreams_Terminated" event (in the early version tests of my App). :-(

So after this event if I check the AStreams and I found it "not initialized".

And I cannot run ...

B4X:
   Starter.AStreams.Write(aBuffer.GetBytes("UTF8"))

I don't understand the reason because after x time (few minutes) the
AsyncStreams is closed (also if I initialize it within the Starter).
So when the app start I can send data and the connection is alive. After x time (of inactivity) the stream is lost.

Is it the OS that terminates the connection or the connected (target device) ?
Is it the connect timeout ?

WFPrinter.Connect(WFPrinterIP, WFPrinterPortNum, 10000)
 
Last edited:
Upvote 0

Computersmith64

Well-Known Member
Licensed User
Longtime User
Did you also move all your comms related events into the service?

- Colin.
 
Upvote 0
Top