92 lines
1.7 KiB
Go
92 lines
1.7 KiB
Go
package udp
|
|
|
|
import (
|
|
"log/slog"
|
|
"net"
|
|
)
|
|
|
|
type UdpClient interface {
|
|
SendMsg(msg UdpMessageEncoder) error
|
|
Send(b []byte) error
|
|
Close()
|
|
}
|
|
|
|
type client struct {
|
|
laddr *net.UDPAddr
|
|
raddr *net.UDPAddr
|
|
conn *net.UDPConn
|
|
}
|
|
|
|
// 新建UDP客户端
|
|
// remoteAddr - 远端地址, 如 127.0.0.1:7777
|
|
func NewClient(remoteAddr string) UdpClient {
|
|
addr, err := net.ResolveUDPAddr("udp", remoteAddr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
var laddr *net.UDPAddr = nil
|
|
conn, err := net.DialUDP("udp", laddr, addr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
c := &client{
|
|
laddr: laddr,
|
|
raddr: addr,
|
|
conn: conn,
|
|
}
|
|
return c
|
|
}
|
|
|
|
// 新建UDP客户端
|
|
// remoteAddr - 远端地址, 如 127.0.0.1:7777
|
|
// localAddr - 本地地址, 如 :9999
|
|
func NewClientWithLocalAddr(remoteAddr string, localAddr string) UdpClient {
|
|
addr, err := net.ResolveUDPAddr("udp", remoteAddr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
laddr, err := net.ResolveUDPAddr("udp", localAddr)
|
|
if err != nil {
|
|
slog.Info("UDP客户端使用随机端口")
|
|
laddr = nil
|
|
}
|
|
conn, err := net.DialUDP("udp", laddr, addr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
c := &client{
|
|
laddr: laddr,
|
|
raddr: addr,
|
|
conn: conn,
|
|
}
|
|
return c
|
|
}
|
|
|
|
func (c *client) SendMsg(msg UdpMessageEncoder) error {
|
|
b := msg.Encode()
|
|
_, err := c.conn.Write(b)
|
|
if err != nil {
|
|
slog.Error("udp client send error", "error", err)
|
|
return err
|
|
}
|
|
return nil
|
|
// slog.Debug("udp client send", "size", n)
|
|
}
|
|
|
|
func (c *client) Send(b []byte) error {
|
|
_, err := c.conn.Write(b)
|
|
if err != nil {
|
|
slog.Error("udp client send error", "error", err)
|
|
return err
|
|
}
|
|
return nil
|
|
// slog.Debug("udp client send", "size", n)
|
|
}
|
|
|
|
func (c *client) Close() {
|
|
err := c.conn.Close()
|
|
if err != nil {
|
|
slog.Error("udp client close error", "error", err)
|
|
}
|
|
}
|