CreateUDPStream ( [port] )
Parameters
| port (optional) - local port to bind the stream to; 0 picks any free port (default) |
Description
|
Creates a UDP stream bound to a local port, for fast connectionless network messages. UDP is the "fire and forget" side of network programming. Unlike a TCP stream there is no connection: one UDP stream can swap packets with any number of machines, each packet stands alone, and delivery is not guaranteed - packets can be lost or arrive out of order. That trade makes UDP the classic choice for the fast, frequent traffic of an action game (player positions, shots fired), where the next update matters more than a lost old one. For anything that must arrive exactly once and in order - a chat line, a file - use a TCP stream instead. The returned handle works with the ordinary stream commands: build a message with WriteLine, WriteInt and friends, fire it with SendUDPMsg, and poll for incoming packets with RecvUDPMsg. A game host binds a port number the players know in advance; a joining player usually passes no port at all and lets the system pick a free one - UDPStreamPort reveals which one it got. Returns 0 if the stream could not be created, most often because another program (or another copy of your game) already has the port - so always check before using the handle. Close the stream with CloseUDPStream when you are done. See also: CloseUDPStream, SendUDPMsg, RecvUDPMsg, UDPStreamPort, UDPTimeouts, OpenTCPStream. |
Example
; CreateUDPStream Example ; ----------------------- ; This program is both ends of a UDP conversation at once: two ; streams on this machine swap a packet over the loopback address. ; The loopback address 127.0.0.1 as a packed integer loopback=(127 Shl 24) Or 1 ; CreateUDPStream binds a UDP stream to a local port and returns ; a handle, or 0 on failure (for example if the port is in use) host=CreateUDPStream(5401) If host=0 Then Print "Could not bind port 5401 (it may be in use)" Else Print "Host: CreateUDPStream(5401) is listening on port "+UDPStreamPort(host) ; With no port given, CreateUDPStream picks any free port player=CreateUDPStream() If player=0 Then Print "Player: could not create a UDP stream" Else Print "Player: CreateUDPStream() was given free port "+UDPStreamPort(player) ; Prove the streams work: write a line, then send it as one packet WriteLine player,"Hello from the player" SendUDPMsg player,loopback,5401 Print "Player: sent a packet to "+DottedIP$(loopback)+":5401" ; Wait up to half a second for the packet to arrive UDPTimeouts 500 from=RecvUDPMsg(host) If from=0 Then Print "Host: no packet arrived" Else Print "Host: received '"+ReadLine$(host)+"' from "+DottedIP$(from) EndIf CloseUDPStream player EndIf CloseUDPStream host Print "Both streams closed" EndIf Print "" Print "Press any key to close the example" WaitKey End
Index