gudp_func.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2017-2018 gf Author(https://github.com/gogf/gf). 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. package gudp
  7. import (
  8. "net"
  9. )
  10. // NewNetConn creates and returns a *net.UDPConn with given addresses.
  11. func NewNetConn(remoteAddress string, localAddress ...string) (*net.UDPConn, error) {
  12. var err error
  13. var remoteAddr, localAddr *net.UDPAddr
  14. remoteAddr, err = net.ResolveUDPAddr("udp", remoteAddress)
  15. if err != nil {
  16. return nil, err
  17. }
  18. if len(localAddress) > 0 {
  19. localAddr, err = net.ResolveUDPAddr("udp", localAddress[0])
  20. if err != nil {
  21. return nil, err
  22. }
  23. }
  24. conn, err := net.DialUDP("udp", localAddr, remoteAddr)
  25. if err != nil {
  26. return nil, err
  27. }
  28. return conn, nil
  29. }
  30. // Send writes data to <address> using UDP connection and then closes the connection.
  31. // Note that it is used for short connection usage.
  32. func Send(address string, data []byte, retry ...Retry) error {
  33. conn, err := NewConn(address)
  34. if err != nil {
  35. return err
  36. }
  37. defer conn.Close()
  38. return conn.Send(data, retry...)
  39. }
  40. // SendRecv writes data to <address> using UDP connection, reads response and then closes the connection.
  41. // Note that it is used for short connection usage.
  42. func SendRecv(address string, data []byte, receive int, retry ...Retry) ([]byte, error) {
  43. conn, err := NewConn(address)
  44. if err != nil {
  45. return nil, err
  46. }
  47. defer conn.Close()
  48. return conn.SendRecv(data, receive, retry...)
  49. }