github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/testing/servers/udp/udp.go (about) 1 package udp 2 3 import ( 4 "fmt" 5 6 "github.com/xmplusdev/xmcore/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 localAddr := conn.LocalAddr().(*net.UDPAddr) 31 return net.UDPDestination(net.IPAddress(localAddr.IP), net.Port(localAddr.Port)), nil 32 } 33 34 func (server *Server) handleConnection(conn *net.UDPConn) { 35 server.accepting = true 36 for server.accepting { 37 buffer := make([]byte, 2*1024) 38 nBytes, addr, err := conn.ReadFromUDP(buffer) 39 if err != nil { 40 fmt.Printf("Failed to read from UDP: %v\n", err) 41 continue 42 } 43 44 response := server.MsgProcessor(buffer[:nBytes]) 45 if _, err := conn.WriteToUDP(response, addr); err != nil { 46 fmt.Println("Failed to write to UDP: ", err.Error()) 47 } 48 } 49 } 50 51 func (server *Server) Close() error { 52 server.accepting = false 53 return server.conn.Close() 54 }