数据上报
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

51 lines
1023 B

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
}
}