Golang 高性能UDP Server實現

經過Goroutine實現UDP消息併發處理併發

package main import ( "net"
    "fmt"
    "os" ) // 限制goroutine數量
var limitChan = make(chan bool, 1000) // UDP goroutine 實現併發讀取UDP數據
func udpProcess(conn *net.UDPConn) { // 最大讀取數據大小
    data := make([]byte, 1024) n, _, err := conn.ReadFromUDP(data) if err != nil { fmt.Println("failed read udp msg, error: " + err.Error()) } str := string(data[:n]) fmt.Println("receive from client, data:" + str) <- 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) }
相關文章
相關標籤/搜索