clientReceiveData() with timeout and bytesToReceive
Posted: Tue Feb 09, 2010 12:48 pm
This has been super handy for me when working with any kind of servers, so I thought I could share it.
It is also handy to use my HEX functions if you're into network programming: http://www.purebasic.fr/english/viewtop ... 12&t=37219
If you don't understand why it is handy then I bet you haven't done much network programming in PB.
You could for example download a whole web page like this:Surely you would have to send the HTTP request first...
It is also handy to use my HEX functions if you're into network programming: http://www.purebasic.fr/english/viewtop ... 12&t=37219
Code: Select all
Procedure.l clientReceiveData(serverID,*buffer,bufferSize,timeout=1000,bytesToReceive=0)
;Will wait until received bytesToReceive or it times out.
;If bytesToReceive = 0 it will wait until the first packet is received or timeout.
;If return value is less than bytesToReceive it means that was all it received before timeout.
;If return value is equal to bytesToReceive it has received everything, but there might be more available.
Protected dataLength, totalData, time
If bytesToReceive > bufferSize
Debug "Get a grip...": End ;it would have caused an invalid memory bug if you really wanted to try
Else
Repeat
Delay(10): time + 10
If NetworkClientEvent(serverID) = #PB_NetworkEvent_Data
dataLength = ReceiveNetworkData(serverId,*buffer+totalData,bufferSize-totalData)
If dataLength > -1
totalData + dataLength
time = 0 ;reset timeout each time we receive data
EndIf
EndIf
Until time >= timeout Or (bytesToReceive=0 And totalData>0) Or (bytesToReceive>0 And totalData>=bytesToReceive)
EndIf
ProcedureReturn totalData
EndProcedure
You could for example download a whole web page like this:
Code: Select all
Repeat ;download until no more packets are available for 2 seconds
bytesReceived = clientReceiveData(serverID,*buffer,bufferSize,2000)
Debug PeekS(*buffer,bytesReceived)
Until totalData <= 0