DTLSServer

Inherits: Reference < Object

Helper class to implement a DTLS server.

Description

This class is used to store the state of a DTLS server. Upon setup it converts connected PacketPeerUDP to PacketPeerDTLS accepting them via take_connection as DTLS clients. Under the hood, this class is used to store the DTLS state and cookies of the server. The reason of why the state and cookies are needed is outside of the scope of this documentation.

Below a small example of how to use it:

  1. # server.gd
  2. extends Node
  3. var dtls := DTLSServer.new()
  4. var server := UDPServer.new()
  5. var peers = []
  6. func _ready():
  7. server.listen(4242)
  8. var key = load("key.key") # Your private key.
  9. var cert = load("cert.crt") # Your X509 certificate.
  10. dtls.setup(key, cert)
  11. func _process(delta):
  12. while server.is_connection_available():
  13. var peer : PacketPeerUDP = server.take_connection()
  14. var dtls_peer : PacketPeerDTLS = dtls.take_connection(peer)
  15. if dtls_peer.get_status() != PacketPeerDTLS.STATUS_HANDSHAKING:
  16. continue # It is normal that 50% of the connections fails due to cookie exchange.
  17. print("Peer connected!")
  18. peers.append(dtls_peer)
  19. for p in peers:
  20. p.poll() # Must poll to update the state.
  21. if p.get_status() == PacketPeerDTLS.STATUS_CONNECTED:
  22. while p.get_available_packet_count() > 0:
  23. print("Received message from client: %s" % p.get_packet().get_string_from_utf8())
  24. p.put_packet("Hello DTLS client".to_utf8())
  1. # client.gd
  2. extends Node
  3. var dtls := PacketPeerDTLS.new()
  4. var udp := PacketPeerUDP.new()
  5. var connected = false
  6. func _ready():
  7. udp.connect_to_host("127.0.0.1", 4242)
  8. dtls.connect_to_peer(udp, false) # Use true in production for certificate validation!
  9. func _process(delta):
  10. dtls.poll()
  11. if dtls.get_status() == PacketPeerDTLS.STATUS_CONNECTED:
  12. if !connected:
  13. # Try to contact server
  14. dtls.put_packet("The answer is... 42!".to_utf8())
  15. while dtls.get_available_packet_count() > 0:
  16. print("Connected: %s" % dtls.get_packet().get_string_from_utf8())
  17. connected = true

Methods

Error

setup ( CryptoKey key, X509Certificate certificate, X509Certificate chain=null )

PacketPeerDTLS

take_connection ( PacketPeerUDP udp_peer )

Method Descriptions

Setup the DTLS server to use the given private_key and provide the given certificate to clients. You can pass the optional chain parameter to provide additional CA chain information along with the certificate.


Try to initiate the DTLS handshake with the given udp_peer which must be already connected (see PacketPeerUDP.connect_to_host).

Note: You must check that the state of the return PacketPeerUDP is PacketPeerDTLS.STATUS_HANDSHAKING, as it is normal that 50% of the new connections will be invalid due to cookie exchange.