DTLSServer
实现DTLS服务器的辅助类。
描述
这个类用来存储DTLS服务器的状态。在setup时,它将连接的PacketPeerUDP转换为PacketPeerDTLS,通过take_connection接受它们作为DTLS客户端。底下,这个类是用来存储服务器的DTLS状态和cookie的。为什么需要状态和cookie的原因不在本文档的范围内。
下面以一个小例子来说明如何使用它。
# server.gd
extends Node
var dtls := DTLSServer.new()
var server := UDPServer.new()
var peers = []
func _ready():
server.listen(4242)
var key = load("key.key") # Your private key.
var cert = load("cert.crt") # Your X509 certificate.
dtls.setup(key, cert)
func _process(delta):
while server.is_connection_available():
var peer : PacketPeerUDP = server.take_connection()
var dtls_peer : PacketPeerDTLS = dtls.take_connection(peer)
if dtls_peer.get_status() != PacketPeerDTLS.STATUS_HANDSHAKING:
continue # It is normal that 50% of the connections fails due to cookie exchange.
print("Peer connected!")
peers.append(dtls_peer)
for p in peers:
p.poll() # Must poll to update the state.
if p.get_status() == PacketPeerDTLS.STATUS_CONNECTED:
while p.get_available_packet_count() > 0:
print("Received message from client: %s" % p.get_packet().get_string_from_utf8())
p.put_packet("Hello DTLS client".to_utf8())
# client.gd
extends Node
var dtls := PacketPeerDTLS.new()
var udp := PacketPeerUDP.new()
var connected = false
func _ready():
udp.connect_to_host("127.0.0.1", 4242)
dtls.connect_to_peer(udp, false) # Use true in production for certificate validation!
func _process(delta):
dtls.poll()
if dtls.get_status() == PacketPeerDTLS.STATUS_CONNECTED:
if !connected:
# Try to contact server
dtls.put_packet("The answer is... 42!".to_utf8())
while dtls.get_available_packet_count() > 0:
print("Connected: %s" % dtls.get_packet().get_string_from_utf8())
connected = true
方法
setup ( CryptoKey key, X509Certificate certificate, X509Certificate chain=null ) | |
take_connection ( PacketPeerUDP udp_peer ) |
方法说明
- Error setup ( CryptoKey key, X509Certificate certificate, X509Certificate chain=null )
设置 DTLS 服务器使用给定的 private_key
并向客户端提供给定的 certificate
。您可以传递可选的 chain
参数,以便在提供证书的同时提供额外的 CA 证书息。
- PacketPeerDTLS take_connection ( PacketPeerUDP udp_peer )
尝试与给定的udp_peer
启动DTLS握手,该peer必须已经连接,参阅PacketPeerUDP.connect_to_host。
注意: 你必须检查返回PacketPeerUDP的状态是否为PacketPeerDTLS.STATUS_HANDSHAKING,因为正常情况下,50%的新连接会因为cookie交换而无效。