github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/p2p/server/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net"
     7  	"time"
     8  )
     9  
    10  func main() {
    11  	listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 9981})
    12  	if err != nil {
    13  		fmt.Println(err)
    14  		return
    15  	}
    16  	log.Printf("本地地址: <%s> \n", listener.LocalAddr().String())
    17  	peers := make([]net.UDPAddr, 0, 2)
    18  	data := make([]byte, 1024)
    19  	for {
    20  		n, remoteAddr, err := listener.ReadFromUDP(data)
    21  		if err != nil {
    22  			fmt.Printf("error during read: %s", err)
    23  		}
    24  		log.Printf("<%s> %s\n", remoteAddr.String(), data[:n])
    25  		peers = append(peers, *remoteAddr)
    26  		if len(peers) == 2 {
    27  
    28  			log.Printf("进行UDP打洞,建立 %s <--> %s 的连接\n", peers[0].String(), peers[1].String())
    29  			listener.WriteToUDP([]byte(peers[1].String()), &peers[0])
    30  			listener.WriteToUDP([]byte(peers[0].String()), &peers[1])
    31  			time.Sleep(time.Second * 8)
    32  			log.Println("中转服务器退出,仍不影响peers间通信")
    33  			return
    34  		}
    35  	}
    36  }