github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/libs/kcp-go/examples/echo.go (about)

     1  package main
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"io"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/xtaci/kcp-go"
    10  	"golang.org/x/crypto/pbkdf2"
    11  )
    12  
    13  func main() {
    14  	key := pbkdf2.Key([]byte("demo pass"), []byte("demo salt"), 1024, 32, sha1.New)
    15  	block, _ := kcp.NewAESBlockCrypt(key)
    16  	if listener, err := kcp.ListenWithOptions("127.0.0.1:12345", block, 10, 3); err == nil {
    17  		// spin-up the client
    18  		go client()
    19  		for {
    20  			s, err := listener.AcceptKCP()
    21  			if err != nil {
    22  				log.Fatal(err)
    23  			}
    24  			go handleEcho(s)
    25  		}
    26  	} else {
    27  		log.Fatal(err)
    28  	}
    29  }
    30  
    31  // handleEcho send back everything it received
    32  func handleEcho(conn *kcp.UDPSession) {
    33  	buf := make([]byte, 4096)
    34  	for {
    35  		n, err := conn.Read(buf)
    36  		if err != nil {
    37  			log.Println(err)
    38  			return
    39  		}
    40  
    41  		n, err = conn.Write(buf[:n])
    42  		if err != nil {
    43  			log.Println(err)
    44  			return
    45  		}
    46  	}
    47  }
    48  
    49  func client() {
    50  	key := pbkdf2.Key([]byte("demo pass"), []byte("demo salt"), 1024, 32, sha1.New)
    51  	block, _ := kcp.NewAESBlockCrypt(key)
    52  
    53  	// wait for server to become ready
    54  	time.Sleep(time.Second)
    55  
    56  	// dial to the echo server
    57  	if sess, err := kcp.DialWithOptions("127.0.0.1:12345", block, 10, 3); err == nil {
    58  		for {
    59  			data := time.Now().String()
    60  			buf := make([]byte, len(data))
    61  			log.Println("sent:", data)
    62  			if _, err := sess.Write([]byte(data)); err == nil {
    63  				// read back the data
    64  				if _, err := io.ReadFull(sess, buf); err == nil {
    65  					log.Println("recv:", string(buf))
    66  				} else {
    67  					log.Fatal(err)
    68  				}
    69  			} else {
    70  				log.Fatal(err)
    71  			}
    72  			time.Sleep(time.Second)
    73  		}
    74  	} else {
    75  		log.Fatal(err)
    76  	}
    77  }