RecvUDPMsg ( udp_stream )
Parameters
| udp_stream - a UDP stream handle returned by CreateUDPStream |
Description
|
Receives the next packet waiting on a UDP stream and returns the sender's IP address. Returns the sender's address as a packed integer (feed it to DottedIP for display), or 0 if no packet is waiting. By default it never blocks, which makes it perfect to poll once per game loop: a 0 simply means "nothing new this frame". If you would rather wait, UDPTimeouts gives every RecvUDPMsg a patience budget in milliseconds. Each successful call delivers exactly one whole packet into the stream's read buffer, which you then pick apart with the ordinary stream commands - ReadLine, ReadInt, ReadAvail and friends, matching whatever the sender wrote before its SendUDPMsg. The next successful call replaces the buffer with the next packet, so read everything you care about before polling again - any unread remainder of the old packet is gone. After a packet arrives, UDPMsgIP and UDPMsgPort report who sent it (UDPMsgIP repeats this command's return value); together they are the return address for a reply. Packets from your own machine work fine, which is why the example can chat with itself over 127.0.0.1. See also: SendUDPMsg, UDPMsgIP, UDPMsgPort, UDPTimeouts, ReadAvail. |
Example
; RecvUDPMsg Example ; ------------------ ; This program is both ends of a UDP conversation at once: two ; streams on this machine swap packets over the loopback address. ; The loopback address 127.0.0.1 as a packed integer loopback=(127 Shl 24) Or 1 host=CreateUDPStream(5404) If host=0 Then Print "Could not bind port 5404 (it may be in use)" Else player=CreateUDPStream() If player=0 Then Print "Player: could not create a UDP stream" Else ; With nothing waiting, RecvUDPMsg returns 0 straight away - ; by default it never blocks, so game loops can poll it Print "Host: RecvUDPMsg with nothing waiting = "+RecvUDPMsg(host) WriteLine player,"Ping from the player" SendUDPMsg player,loopback,5404 Print "Player: packet sent" ; Poll until the packet arrives - RecvUDPMsg returns the ; sender's IP address, or 0 if no packet is waiting from=0 For try=1 To 50 from=RecvUDPMsg(host) If from<>0 Then Exit Delay 10 Next If from=0 Then Print "Host: no packet arrived" Else Print "Host: packet from "+DottedIP$(from)+" after "+try+" poll(s)" ; The packet's content is read with the usual stream commands Print "Host: message = '"+ReadLine$(host)+"'" EndIf CloseUDPStream player EndIf CloseUDPStream host EndIf Print "" Print "Press any key to close the example" WaitKey End
Index