server.go 970 Bytes
Newer Older
barnettZQG's avatar
barnettZQG committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
package main

import (
	"fmt"
	"net"
	"os"

	"github.com/sirupsen/logrus"
)

// 限制goroutine数量
var limitChan = make(chan bool, 1000)

// UDP goroutine 实现并发读取UDP数据
func udpProcess(conn *net.UDPConn, index int) {
	// 最大读取数据大小
	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)
	conn.Write([]byte(fmt.Sprintf("receive %d", index)))
	<-limitChan
}

func udpServer(address string) {
	udpAddr, err := net.ResolveUDPAddr("udp", address)
	logrus.Infof("listen %s", 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)
	}
	var n = 0
	for {
		limitChan <- true
		go udpProcess(conn, n)
		n++
	}
}

func main() {
	address := "0.0.0.0:8080"
	udpServer(address)
}