|
| 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 | + ConnectionIDGenerator: dtls.RandomCIDGenerator(8), |
| 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 | +} |
0 commit comments