github.com/gogf/gf@v1.16.9/net/gudp/gudp_func.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gudp 8 9 import ( 10 "net" 11 ) 12 13 // NewNetConn creates and returns a *net.UDPConn with given addresses. 14 func NewNetConn(remoteAddress string, localAddress ...string) (*net.UDPConn, error) { 15 var err error 16 var remoteAddr, localAddr *net.UDPAddr 17 remoteAddr, err = net.ResolveUDPAddr("udp", remoteAddress) 18 if err != nil { 19 return nil, err 20 } 21 if len(localAddress) > 0 { 22 localAddr, err = net.ResolveUDPAddr("udp", localAddress[0]) 23 if err != nil { 24 return nil, err 25 } 26 } 27 conn, err := net.DialUDP("udp", localAddr, remoteAddr) 28 if err != nil { 29 return nil, err 30 } 31 return conn, nil 32 } 33 34 // Send writes data to <address> using UDP connection and then closes the connection. 35 // Note that it is used for short connection usage. 36 func Send(address string, data []byte, retry ...Retry) error { 37 conn, err := NewConn(address) 38 if err != nil { 39 return err 40 } 41 defer conn.Close() 42 return conn.Send(data, retry...) 43 } 44 45 // SendRecv writes data to <address> using UDP connection, reads response and then closes the connection. 46 // Note that it is used for short connection usage. 47 func SendRecv(address string, data []byte, receive int, retry ...Retry) ([]byte, error) { 48 conn, err := NewConn(address) 49 if err != nil { 50 return nil, err 51 } 52 defer conn.Close() 53 return conn.SendRecv(data, receive, retry...) 54 }