package main
import (
"fmt"
"net"
"os"
)
// 限制goroutine数量
var limitChan = make(chan bool, 1000)
// UDP goroutine 实现并发读取UDP数据
func udpProcess(conn *net.UDPConn) {
data := make([]byte, 1024)
n,remoteAddr,err := conn.ReadFromUDP(data)
if err != nil {
fmt.Println("Failed To Read UDP Msg, Error: " + err.Error())
}
str := string(data[:n])
fmt.Println("Reveive From Client, Data: " + str)
conn.WriteToUDP([]byte(str), remoteAddr)
<- limitChan
}
func udpServer(address string) {
udpAddr, err := net.ResolveUDPAddr("udp", address)
conn, err := net.ListenUDP("udp", udpAddr)
defer conn.Close()
if err != nil {
fmt.Println("Read From Connect Failed, Err :" + err.Error())
os.Exit(1)
}
for {
limitChan <- true
go udpProcess(conn)
}
}
func main() {
address := "0.0.0.0:8080"
udpServer(address)
}
有疑问加站长微信联系(非本文作者)