Page 1 of 1

sockets, howto "read while"...?

Posted: Mon Feb 20, 2012 10:13 am
by josemv
Hi

first thanks for your help and patience. Your advice it is being really useful to help me to understand how Livecode works. Am reading manuals, forum posts and checking every video but takes some time to understand it.

Using sockets, when connect to servers to get information, rule says they will return lines finished with cr+lf. But...

1- how to still reading while there are data available?
2- how close connection after a reasonable ammount of time? lets say 5-10 seconds.
3-Livecode approach to handle sockets looks a bit confusing to me and considering am new to the language too... I have all ingredients to get it not working. What's the way to translate this php code to livecode? I tried checking by EOF but doesn't works.

Code: Select all

try{
  $conn = fsockopen($server, 80);  //server name and port
}

catch(Exception $e){
  return FALSE;
}
		
fputs($conn, $request."\r\n");
$response = "";

while(!feof($conn)){ 
  $response .= fgets($con, 128); 
}

fclose($conn);
Thanks
Jose

Re: sockets, howto "read while"...?

Posted: Mon Feb 20, 2012 4:50 pm
by Mark
Hi Jose,

Here's an example:

Code: Select all

on connect
	put "123.123.123.123" into myServer
	put "80" into myPort
	put myServer & colon & myPort into mySock
	open socket mySock
	put the result into rslt
	if rslt is empty then
		put "This is some request" & crlf into myRequest
		write myRequest to socket mySock
		read from socket mySock with message "received"
		send "closeConnection mySock" to my in 10 seconds
	else
		beep
		answer error rslt
	end if
end connect

// this handler reads all data at once
// probably you don't need to check for eof
on received theIP,theMsg
	put theMsg into myResponse
	// do something with myResponse here
end received

on closeConnection theSock
  if theSock is among the lines of the opensockets then
  	close socket theSock
  end if
end closeConnection
  
// catch
on socketError theSock,theError
  beep
  answer error theError && "while connecting to" && theSock
 end socketError
 
on socketTimeout theSock
	beep
	answer error "Could not connect to" && theSock
end socketTimeout
I didn't test this code. It just shows the basics and should work with some minor adjustments.

Kind regards,

Mark

Re: sockets, howto "read while"...?

Posted: Wed Feb 22, 2012 10:01 am
by josemv
Hi Mark,

wow, great advices. Thanks so much.

I didn't checked yet but will let you know how works.

Jose