How do I use sockets synchronously?

124 views
Skip to first unread message

MSmithDev

unread,
Sep 29, 2020, 11:34:42 AM9/29/20
to Flutter Development (flutter-dev)
I'm working on an app that will take data from a cnc machine using a type of query over a TCP socket. For example if I send "?Q100" over the socket the machine would respond with " SERIAL NUMBER, 1234567" 

My issue is that the Socket class uses a callback when it receives data. I need to be able to send a command, wait for a response, then return that value. The timing is important because if i send several commands the order in which they are received matters because there is no identifier for the returned data.

I was looking at the RawSocketSyncronous but i'm not sure how to implement a readLine method for that since it just has a read method for getting bytes from the socket.

Any advice would be appreciated!

Kelly Burkhart

unread,
Nov 4, 2020, 11:14:00 PM11/4/20
to Flutter Development (flutter-dev)
I’m new to flutter, but know a fair amount about TCP and sockets.  A TCP stream is an ordered byte stream which implies that you don’t read “messages” you read however many bytes are available to read.  This means that in your dart code you will need to wrap your socket reads within logic that accumulates new data received via callback and emits a callback for each new “message”.  Your code will be responsible for scanning the bytes read and splitting them into whatever you consider a message (by separating by \r\n or whatever separates messages from the server).  It is quite possible, regardless of if you’re operating synchronously or not that you will read a partial message and it will take multiple read callbacks before you can emit a new message callback.

Assuming that in Dart, callbacks are guaranteed to be received in the same order they were sent you should not have issue with reconciling requests from responses, even if you write and read asynchronously.

-K
Reply all
Reply to author
Forward
0 new messages