登录
首页 >  Golang >  Go问答

优化 UDP 数据包每秒传输速度的 Go 编程技巧

来源:stackoverflow

时间:2024-03-04 21:21:26 207浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《优化 UDP 数据包每秒传输速度的 Go 编程技巧》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在尝试用 go 编写一个简单的中继服务器,以便在两个客户端之间发送游戏数据。客户端发送 udp 注册消息,其中包含协议 id,后跟其匹配 id 和客户端 id;这些消息用于设置地址的哈希映射,以便当标准(游戏数据)消息到达时,我们可以将其映射到其预先注册的接收者(无需在每条消息中发送该数据)。 (我正在使用 github.com/cornelk/hashmap,如果这有什么区别,并且服务器是 highcpu-16 gcp 计算实例)

此设置适用于少量客户端(每秒约 30 条消息)。然而,当我加大负载测试时,传出带宽会随着传入带宽的持续上升而趋于平稳。我已经使用 vmstatifstat 进行了日志记录(以及一些 dropwatch 监控,这表明在软件级别有很多数据包被丢弃)。在我看来,数据包正在被丢弃,因为我的 go 服务器读取它们的速度不够快。

最初,我为每个 cpu 核心使用一个 goroutine:

runtime.gomaxprocs(runtime.numcpu())

connection, err := net.listenudp("udp", &addr)
if err != nil {
    panic(err)
}

for i := 0; i < runtime.numcpu(); i++ {
    go listen(connection, c)
}

我还尝试过重用端口并分别监听每个 goroutine(使用 github.com/libp2p/go-reuseport 包)。

最后,我尝试为传入和传出消息设置缓冲通道,以尽量减少监听 goroutine 不拉取消息的时间。

在尝试同时处理 10 万玩家时,我错过了什么?感觉无论我的方法如何,我都无法在不丢失大量数据包的情况下超过大约 3000 名玩家。

我的 listen 函数已经经历了多次迭代,徒劳地尝试提高每秒数据包数,但通常是:

// Emits SIGABRT to the interrupts channel if an error occurs outside of individual message handling.
func listen(connection *net.UDPConn, interrupts chan os.Signal/*, inbox chan IncomingMessage*/) {
    buffer := make([]byte, 1024)
    n, remoteAddr, err := 0, new(net.UDPAddr), error(nil)
    for err == nil {
        n, remoteAddr, err = connection.ReadFromUDP(buffer)
        if err != nil {
            continue
        }

        //log.Println("Received", n, "bytes", hex.EncodeToString(buffer[:n]))
        if n < 2 {
            log.Println("Minimum packet length is 2 bytes. Received a packet of length", n, "bytes")
            continue
        }

        //inbox<-IncomingMessage{
        //    sender: remoteAddr,
        //    data:   append([]byte(nil), buffer[:n]...),
        //}

        //go handlePacket(inbox, remoteAddr, append([]byte(nil), buffer[:n]...), n)

        protocolId := binary.LittleEndian.Uint16(buffer)
        if protocolId == registrationProtocolId {
            // Start a goroutine to handle the packet (copy the buffer minus the protocol id))
            //go handleRegistrationPacket(connection, remoteAddr, append([]byte(nil), buffer[:n]...))
            handleRegistrationPacket(outbox, remoteAddr, buffer[:n])
        } else if protocolId == matchProtocolId {
            //go handleStandardPacket(connection, remoteAddr.String(), append([]byte(nil), buffer[:n]...))
            handleStandardPacket(outbox, remoteAddr.String(), buffer[:n])
        } else {
            log.Println("Unrecognised protocol id: ", protocolId)
        }
    }
    log.Println("Listener failed:", err)
    interrupts<-syscall.SIGABRT
}

此图表显示 1600 个并发游戏(3200 个客户端)。过了某个点,传出的 kb/s 就会停止攀升。 cpu甚至没有出汗。


解决方案


我重新阅读了 How to receive a million packets per second,这表明在套接字上使用 so_reuseport 选项是正确的方法。在下面的代码中,我使用机器的每个核心一个连接(在我的例子中为 16 个),每个连接使用 4 个发件箱处理程序。 cpu 使用率稍高,每个连接 4 个,但似乎比每个连接 1 个更可靠(尽管需要测试和明确的答案)。

下面没有显示的是 listen 函数启动 goroutine 来处理传入的消息并立即返回监听。 outbox 被传递到处理函数作为发送消息的方式。

type OutgoingMessage struct {
    recipient *net.UDPAddr
    data      []byte
}

// ...

func beginListen(c chan os.Signal) {
    addr := net.UDPAddr{
        Port: 1234,
        IP:   net.IP{0, 0, 0, 0},
    }

    connection, err := reuseport.ListenPacket("udp", addr.String())

    if err != nil {
        panic(err)
    }

    outbox := make(chan OutgoingMessage, maxQueueSize)

    sendFromOutbox := func() {
        n, err := 0, error(nil)
        for msg := range outbox {
            n, err = connection.(*net.UDPConn).WriteToUDP(msg.data, msg.recipient)
            if err != nil {
                panic(err)
            }
            if n != len(msg.data) {
                log.Println("Tried to send", len(msg.data), "bytes but only sent ", n)
            }
        }
    }

    for i := 1;  i <= 4; i++ {
        go sendFromOutbox()
    }

    listen(connection.(*net.UDPConn), c, outbox)

    close(outbox)
}

func main() {
    log.Println("Starting...")

    runtime.GOMAXPROCS(runtime.NumCPU())

    c := make(chan os.Signal, 1)

    for i := 0; i < runtime.NumCPU(); i++ {
        go beginListen(c)
    }

    // ...
}

下图显示了与之前的差异:

(到目前为止,这是一个峰值;变量名称不会保留,我知道我应该继续写入未发送的字节,直到发送所有数据。)

以上就是《优化 UDP 数据包每秒传输速度的 Go 编程技巧》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>