Setting Timeout for recieving data from server

New to FreeBASIC? Post your questions here.
Post Reply
Zero_Divide
Posts: 3
Joined: Mar 31, 2007 21:02

Setting Timeout for recieving data from server

Post by Zero_Divide »

I have this little SUB that sends a request to the server and receives data.

But its getting screwed sometimes because of there is no data actually being received, and program just hangs waiting for it.
I tried using threads but it worked kind off weird

It looks awkward but it generally works.
Is there a way to make it without multi threading, speciafying some timeout value??

Code: Select all

dim shared s as SOCKET
dim shared recvbuffer as zstring * RECVBUFFLEN+1
dim shared bytes as integer
Dim Shared terminate As Integer =0
Dim Shared rec As Integer =0


Sub sendrecieve 
 dim sendbuffer as string
 
 sendBuffer = chr(&HFF, &HFF ,&HFF ,&HFF ,&H67 ,&H65 ,&H74 ,&H73 ,&H74 ,&H61 ,&H74 ,&H75 ,&H73 ,&H0A )
    
    print "send:"; sendbuffer
    
    sleep
    if( send( s, strptr( sendBuffer ), len( sendBuffer ), 1000 ) = SOCKET_ERROR ) then
		print "Error:"; WSAGetLastError; " Calling: send()"
		closesocket( s )
		sleep
        end 1
	end if
        bytes = recv( s, strptr( recvbuffer ), RECVBUFFLEN, 0 )
       	recvbuffer[bytes] = 0
    print "REC!"
    sleep
    rec=1
End Sub

...........
...........
...........

rec=0
for i=1 to 5
Print "Request: "; i
thread=threadcreate(@sendrecieve)  
sleep 1000
if rec=1 then exit for
next

if rec=0 then print "Error:No data recieved"
Vendan
Posts: 48
Joined: Sep 18, 2006 0:25

Post by Vendan »

After you make the socket and connect and all, but before you call recv(), call this function

Code: Select all

dim timeout as integer
timeout = 15000
setsockopt(s ,SOL_SOCKET, SO_RCVTIMEO, value, len(value))
That'll make it timeout on the recv() call if it takes more then 15 seconds.
cha0s
Site Admin
Posts: 5319
Joined: May 27, 2005 6:42
Location: USA
Contact:

Post by cha0s »

In the example above me, I assume he used 's' for a socket descriptor and 'value' should probably be 'timeout'.
Zero_Divide
Posts: 3
Joined: Mar 31, 2007 21:02

Post by Zero_Divide »

This is what i figured out is working.
There should be a pointer when passing timeout value

Code: Select all

Dim timeout As Integer =100
setsockopt(s ,SOL_SOCKET, SO_RCVTIMEO, @timeout, Len(timeout))
Post Reply