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