package dbHelper import ( "fmt" "log" "net" "time" ) type UdpHelper struct { Host string Port int client *net.UDPConn } func (the *UdpHelper) Initial() { addrStr := fmt.Sprintf("%s:%d", the.Host, the.Port) serverAddr, err := net.ResolveUDPAddr("udp", addrStr) if err != nil { log.Println("解析地址失败:", err) panic(err) } // 创建UDP连接 the.client, err = net.DialUDP("udp", nil, serverAddr) if err != nil { log.Println("连接服务器失败:", err) panic(err) } time.Sleep(time.Second * 1) } func (the *UdpHelper) Publish(messageBytes []byte) { if the.client != nil { // 发送数据 _, err := the.client.Write(messageBytes) if err != nil { log.Println("发送数据失败:", err) return } log.Printf("[%v]推送Msg 长度=%d ", the.client.RemoteAddr(), len(messageBytes)) } } func (the *UdpHelper) Close() { err := the.client.Close() if err != nil { log.Printf("[%v] udp 链接 关闭出现异常 %s", the.client.RemoteAddr(), err.Error()) return } }