| udp_stream - a UDP stream handle returned by CreateUDPStream |
|
Returns the local port a UDP stream is bound to - the port it sends from and listens on. When you created the stream with a fixed port, this simply confirms it. It earns its keep when you let CreateUDPStream pick: passing no port (or 0) binds whatever was free, and UDPStreamPort is the only way to find out which port that was - handy for a debug overlay, a log line, or telling another local program where to reach you. In a typical game only the host needs a well-known port; each player's stream takes a free one, and the host learns it anyway from UDPMsgPort when the player's first packet arrives. The example creates one stream of each kind and shows the two port reports side by side. See also: UDPStreamIP, CreateUDPStream, UDPMsgPort, RecvUDPMsg. |
; UDPStreamPort 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
; A game host binds a port every player knows in advance...
host=CreateUDPStream(5408)
If host=0 Then
Print "Could not bind port 5408 (it may be in use)"
Else
Print "Host: UDPStreamPort = "+UDPStreamPort(host)+" (the port we asked for)"
; ...but a player stream can let the system pick any free port,
; and UDPStreamPort reveals which one it was given
player=CreateUDPStream()
If player=0 Then
Print "Player: could not create a UDP stream"
Else
Print "Player: UDPStreamPort = "+UDPStreamPort(player)+" (picked automatically)"
WriteLine player,"Joining from a random port"
SendUDPMsg player,loopback,5408
UDPTimeouts 500
If RecvUDPMsg(host)=0 Then
Print "Host: no packet arrived"
Else
Print "Host: message = '"+ReadLine$(host)+"'"
Print "Host: sender's port "+UDPMsgPort(host)+" matches the player's port above"
EndIf
CloseUDPStream player
EndIf
CloseUDPStream host
EndIf
Print ""
Print "Press any key to close the example"
WaitKey
End