github.com/pion/dtls/v2@v2.2.12/examples/dial/psk/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 client 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  	//
    22  	// Everything below is the pion-DTLS API! Thanks for using it ❤️.
    23  	//
    24  
    25  	// Prepare the configuration of the DTLS connection
    26  	config := &dtls.Config{
    27  		PSK: func(hint []byte) ([]byte, error) {
    28  			fmt.Printf("Server's hint: %s \n", hint)
    29  			return []byte{0xAB, 0xC1, 0x23}, nil
    30  		},
    31  		PSKIdentityHint:      []byte("Pion DTLS Server"),
    32  		CipherSuites:         []dtls.CipherSuiteID{dtls.TLS_PSK_WITH_AES_128_CCM_8},
    33  		ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
    34  	}
    35  
    36  	// Connect to a DTLS server
    37  	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    38  	defer cancel()
    39  	dtlsConn, err := dtls.DialWithContext(ctx, "udp", addr, config)
    40  	util.Check(err)
    41  	defer func() {
    42  		util.Check(dtlsConn.Close())
    43  	}()
    44  
    45  	fmt.Println("Connected; type 'exit' to shutdown gracefully")
    46  
    47  	// Simulate a chat session
    48  	util.Chat(dtlsConn)
    49  }