go项目脚手架
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.
sorbet/pkg/app/udp.go

63 lines
979 B

package app
import (
"context"
"errors"
"io"
"net"
)
// 通过 UDP 协议实现外部通信
var pc net.PacketConn
func initUdp(args []string) {
// 未开启 udp
if !boolArg(args, "--udp") {
return
}
// 这一步属于初始化,切不可放到 OnStart 里面
sizeLimit := intArg(args, "--payload", 1024<<2)
addr := strArg(args, "--addr", ":1324")
// 当程序启动时开启 udp 服务器
OnStart(func() {
listenUDP(addr, sizeLimit)
})
OnStop(freeUdp)
}
func freeUdp() {
if pc != nil {
err := pc.Close()
pc = nil
check(err)
}
}
func listenUDP(address string, maxSize int) {
var err error
pc, err = net.ListenPacket("udp", address)
check(err)
async(func(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
}
buf := make([]byte, maxSize)
n, addr, err := pc.ReadFrom(buf)
if err != nil {
if errors.Is(err, io.EOF) {
return
}
continue
}
recv(pc, addr, buf[:n])
}
})
}