2023-10-19 09:33:40 +08:00
|
|
|
package udp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log/slog"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
type UdpClient interface {
|
|
|
|
SendMsg(msg UdpMessageEncoder)
|
|
|
|
Send(b []byte)
|
2023-10-26 15:06:26 +08:00
|
|
|
Close()
|
2023-10-19 09:33:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
b := msg.Encode()
|
|
|
|
_, err := c.conn.Write(b)
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("udp client send error", "error", err)
|
|
|
|
}
|
|
|
|
// slog.Debug("udp client send", "size", n)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *client) Send(b []byte) {
|
|
|
|
_, err := c.conn.Write(b)
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("udp client send error", "error", err)
|
|
|
|
}
|
|
|
|
// slog.Debug("udp client send", "size", n)
|
|
|
|
}
|
2023-10-26 15:06:26 +08:00
|
|
|
|
|
|
|
func (c *client) Close() {
|
|
|
|
err := c.conn.Close()
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("udp client close error", "error", err)
|
|
|
|
}
|
|
|
|
}
|