B4J Question How to wait (blocking) for network response?

MathiasM

Active Member
Licensed User
Hello

I need to set up a socket connection and send some data, in a lot of cases, a response is expected. I want a blocking request.

What I want, is to use this code:
B4X:
Dim MyData As String = FetchMyData("please")

FetchMyData should send some info over a socket, wait for a response and return the data.
I have 2 problems:
  1. The AsyncStream event isn't tied to a specific command I'm sending. Can I send a command and use Wait For?
  2. If answer on the above is Yes, is it possible to wait for the command and then return the data without being a resumable sub?
For ease for the end user, I would really love the fact that the user can call FetchMyData("please") and not Wait For (FetchMyData("please")) Complete (MyData As String)

So, it is possible to turn a resumeable sub in a normal sub? Maybe with a middlemen function or anything?

Thanks for any input or ideas.
 

KMatle

Expert
Licensed User
Longtime User
AsynStream(s) doesn't return anything so I would do a "handshake". The receiver get's the message and returns an "OK" or so (with a unique message identifier). So you could create a queue (requests without a reply) in a map or so and start a timer to check the queue.

Then there are two cases:

1. The receiver anwers -> delete it from the queue and everything is fine
2. The timer ticks and your code checks for "unanswered" messages
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
If answer on the above is Yes, is it possible to wait for the command and then return the data without being a resumable sub?
Of course not. Blocking the main thread until data is available leads to unresponsive and unreliable programs. Something that was acceptable in the 90s. Not today. Modern operating systems will quick the app very quickly.

1. You should learn how to call a resumable sub and wait for the result. Very simple.
2. You can wait for (almost) any event you like.
B4X:
AStream.Write(data)
Wait For AStream_NewData(buffer() As Byte)
'Work with buffer.
'if you are not using prefix mode, and I have a feeling that you aren't, then this code is broken. Better solution to call it inside a loop and collect the data with B4XBytesBuilder.
 
Upvote 0
Top