github.com/zhongdalu/gf@v1.0.0/g/net/gudp/gudp_func.go (about)

     1  // Copyright 2017-2018 gf Author(https://github.com/zhongdalu/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/zhongdalu/gf.
     6  
     7  package gudp
     8  
     9  import (
    10  	"net"
    11  )
    12  
    13  // 创建标准库UDP链接操作对象
    14  func NewNetConn(raddr string, laddr ...string) (*net.UDPConn, error) {
    15  	var err error
    16  	var remoteAddr, localAddr *net.UDPAddr
    17  	remoteAddr, err = net.ResolveUDPAddr("udp", raddr)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  	if len(laddr) > 0 {
    22  		localAddr, err = net.ResolveUDPAddr("udp", laddr[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  // (面向短链接)发送数据
    35  func Send(addr string, data []byte, retry ...Retry) error {
    36  	conn, err := NewConn(addr)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	defer conn.Close()
    41  	return conn.Send(data, retry...)
    42  }
    43  
    44  // (面向短链接)发送数据并等待接收返回数据
    45  func SendRecv(addr string, data []byte, receive int, retry ...Retry) ([]byte, error) {
    46  	conn, err := NewConn(addr)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	defer conn.Close()
    51  	return conn.SendRecv(data, receive, retry...)
    52  }
    53  
    54  // 判断是否是超时错误
    55  func isTimeout(err error) bool {
    56  	if err == nil {
    57  		return false
    58  	}
    59  	if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
    60  		return true
    61  	}
    62  	return false
    63  }