How to use UDP Server?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By roma

How to use UDP Server?
I looked at the wiki, but I didn’t understand how the server can accept the client’s message already from a known IP address, because in the example it is possible to accept it only from an unknown IP. When I looked at the API reference, I didn’t understand anything about this in the poll() function description: And packet from known address/port pair will be delivered to the appropriate PacketPeerUDP.
How will a packet from a known address/port pair be delivered to the appropriate PacketPeerUDP? Як його назначити? I did not understand anything, please help!

:bust_in_silhouette: Reply From: jgodfrey

I agree that some of the networking documentation is somewhat confusing and should likely be improved. And, while I’m not expert here, I’ll try to offer some input.

First, if you take a look at the example client and server code shown in the docs, it’ll help to clarify some things…

For the confusion on the “known” and “unknown” ip addresses… The server handles that on its own. So, the first time a client makes a connection to the server, it’s an UNKNOWN address (the server hasn’t yet seen it). From the sample code mentioned above, that situation triggers the if server.is_connection_available(): block of code shown below…

func _process(delta):
    server.poll() # Important!
    if server.is_connection_available():
        var peer : PacketPeerUDP = server.take_connection()
        var packet = peer.get_packet()
        print("Accepted peer: %s:%s" % [peer.get_packet_ip(), peer.get_packet_port()])
        print("Received data: %s" % [packet.get_string_from_utf8()])
        # Reply so it knows we received the message.
        # Keep a reference so we can keep contacting the remote peer.

Any given ip address is only UNKNOWN the first time it contacts the server. From the point on, it’s a KNOWN address (and will not trigger the above section of code). Notice in the above, the peer is stored in an array for future communication with that (now KNOWN) address, which happens in the loop shown just below the above code. Specifically, this (from the sample server):

for i in range(0, peers.size()):
    pass # Do something with the connected peers

That runs through the KNOWN connections and does whatever communication may be necessary.