github.com/imannamdari/v2ray-core/v5@v5.0.5/testing/servers/udp/udp.go (about) 1 package udp 2 3 import ( 4 "fmt" 5 6 "github.com/imannamdari/v2ray-core/v5/common/net" 7 ) 8 9 type Server struct { 10 Port net.Port 11 MsgProcessor func(msg []byte) []byte 12 accepting bool 13 conn *net.UDPConn 14 } 15 16 func (server *Server) Start() (net.Destination, error) { 17 conn, err := net.ListenUDP("udp", &net.UDPAddr{ 18 IP: []byte{127, 0, 0, 1}, 19 Port: int(server.Port), 20 Zone: "", 21 }) 22 if err != nil { 23 return net.Destination{}, err 24 } 25 server.Port = net.Port(conn.LocalAddr().(*net.UDPAddr).Port) 26 fmt.Println("UDP server started on port ", server.Port) 27 28 server.conn = conn 29 go server.handleConnection(conn) 30 31 localAddr := conn.LocalAddr().(*net.UDPAddr) 32 return net.UDPDestination(net.IPAddress(localAddr.IP), net.Port(localAddr.Port)), nil 33 } 34 35 func (server *Server) handleConnection(conn *net.UDPConn) { 36 server.accepting = true 37 for server.accepting { 38 buffer := make([]byte, 2*1024) 39 nBytes, addr, err := conn.ReadFromUDP(buffer) 40 if err != nil { 41 fmt.Printf("Failed to read from UDP: %v\n", err) 42 continue 43 } 44 45 response := server.MsgProcessor(buffer[:nBytes]) 46 if _, err := conn.WriteToUDP(response, addr); err != nil { 47 fmt.Println("Failed to write to UDP: ", err.Error()) 48 } 49 } 50 } 51 52 func (server *Server) Close() error { 53 server.accepting = false 54 return server.conn.Close() 55 }