github.com/pion/dtls/v2@v2.2.12/examples/listen/selfsign/main.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 // Package main implements an example DTLS server using self-signed certificates. 5 package main 6 7 import ( 8 "context" 9 "crypto/tls" 10 "fmt" 11 "net" 12 "time" 13 14 "github.com/pion/dtls/v2" 15 "github.com/pion/dtls/v2/examples/util" 16 "github.com/pion/dtls/v2/pkg/crypto/selfsign" 17 ) 18 19 func main() { 20 // Prepare the IP to connect to 21 addr := &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4444} 22 23 // Generate a certificate and private key to secure the connection 24 certificate, genErr := selfsign.GenerateSelfSigned() 25 util.Check(genErr) 26 27 // Create parent context to cleanup handshaking connections on exit. 28 ctx, cancel := context.WithCancel(context.Background()) 29 defer cancel() 30 31 // 32 // Everything below is the pion-DTLS API! Thanks for using it ❤️. 33 // 34 35 // Prepare the configuration of the DTLS connection 36 config := &dtls.Config{ 37 Certificates: []tls.Certificate{certificate}, 38 ExtendedMasterSecret: dtls.RequireExtendedMasterSecret, 39 // Create timeout context for accepted connection. 40 ConnectContextMaker: func() (context.Context, func()) { 41 return context.WithTimeout(ctx, 30*time.Second) 42 }, 43 } 44 45 // Connect to a DTLS server 46 listener, err := dtls.Listen("udp", addr, config) 47 util.Check(err) 48 defer func() { 49 util.Check(listener.Close()) 50 }() 51 52 fmt.Println("Listening") 53 54 // Simulate a chat session 55 hub := util.NewHub() 56 57 go func() { 58 for { 59 // Wait for a connection. 60 conn, err := listener.Accept() 61 util.Check(err) 62 // defer conn.Close() // TODO: graceful shutdown 63 64 // `conn` is of type `net.Conn` but may be casted to `dtls.Conn` 65 // using `dtlsConn := conn.(*dtls.Conn)` in order to to expose 66 // functions like `ConnectionState` etc. 67 68 // Register the connection with the chat hub 69 if err == nil { 70 hub.Register(conn) 71 } 72 } 73 }() 74 75 // Start chatting 76 hub.Chat() 77 }