Page 1 of 1

Reading socket data

Posted: Mon Mar 08, 2021 12:25 pm
by odysseus
I am using sockets in my project, and I can open sockets and transmit and receive data successfully. However, is there a way of detecting if data is available to be read, other than regular polling? I can accept connection on a port, and initiate a handler when the socket is opened from the other end, but then I don't know when data has been sent to me, other than polling. If I poll and there is nothing there I will just have to wait for timeout every time, which is not what I want.

There seem to be a very limited number of socket operations available, compared with the SocketTools suite for example, unless there are more which are undocumented.

Any help would be appreciated.

Re: Reading socket data

Posted: Fri Mar 19, 2021 2:10 pm
by prometheus
You don't need to do a polling, you can use the open, read and write operations using its async form:

Code: Select all

read from socket <socketID> [until <string> | for <amount> [<chunkType>]] [with message <callbackMessage>]
whenever you use this operations with this form (with message <callbackMessage>) you´ll get the <callbackMessage> on the control that invoked the operation, for example you can do this in a button :


Code: Select all

on mouseUp
   --Opens a connection to www.google.com on port 80 and once stablished 
   --it sends the message "connectedToGoogle " back to this control
   open socket "www.google.com:80" with message "connectedToGoogle"  
end mouseUp



--We get this message once the connection has been stablished and  pSocketID contanins the connection id
on connectedToGoogle pSocketID
   read from socket pSocketID  with message "socketFinishedReading"
   write "test" to socket pSocketID with message "socketFinishedWriting"
end connectedToGoogle 



on socketFinishedReading pSocketID, pData
   answer "The socket has been read"
   put pData
   close socket pSocketID
end socketFinishedReading


on socketFinishedWriting pSocketID
   
   answer "The socket has been written"
end socketFinishedWriting  



This way it's non-blocking and you'll be able to write your own protocol very easy, but if you need to read the socket for a common protocol such as http, smtp, ftp etc.. you can use tsnet which is basically a port of curl (if you have a licensed version of livecode) and for http and ftp operations on Livecode Community you may use libURL

Re: Reading socket data

Posted: Fri Mar 19, 2021 4:52 pm
by richmond62
My problem (well, OK, I admit it, I have lots of problems, but most are not totally relevant to LiveCode)
with sockets is how one determines which socket a USB thing (i.e. floor robot) is using.

Re: Reading socket data

Posted: Fri Mar 19, 2021 5:20 pm
by dunbarx
Richmond.

Does the "openSockets" function help you?

Craig

Re: Reading socket data

Posted: Fri Mar 19, 2021 5:45 pm
by Klaus
Doesn't -> the opensockets only return a list of sockets that WE have opened via script?