Golang:将 Gin 与 UDP 服务器混合

Golang: Mixing Gin with an UDP server

我正在尝试同时使用 UDP 服务器连续侦听数据报和 http 服务器,但从未到达字符串 "UDP server up and listening on port..." 和命令 "server.Run()"。

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
    "net"
)

func handleUDPConnection(conn *net.UDPConn) {
    buffer := make([]byte, 8096)
    n, addr, err := conn.ReadFromUDP(buffer)

    if err != nil {
        log.Fatal(err)
    } else {
        fmt.Println("UDP client: ", addr)
        fmt.Println("Received from UDP client: ", string(buffer[:n]))
    }
}

func main() {
    server := gin.Default()
    host, port := "localhost", "41234"
    udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%s", host, port))

    if err != nil {
        log.Fatal(err)
    }

    conn, err := net.ListenUDP("udp", udpAddr)
    if err != nil {
        log.Fatal(err)
    }

    defer conn.Close()
    server.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "pong"})
    })

    for {
        handleUDPConnection(conn)
    }

    fmt.Sprintf("UDP server up and listening on port %s\n", port)
    server.Run()
}

我怎样才能让它发挥作用?

您的代码中存在无限循环。

for {
    handleUDPConnection(conn)
}

这将重复调用 handleUDPConnection 函数,直到程序退出而不会继续

fmt.Sprintf("UDP server up and listening on port %s\n", port)
server.Run()

也许您想在 go 线程中处理连接。这将更像这样:

//define an exit variable
keepListening := true
//spawn a go routine (starts the function on another thread*)
go func() {
    for keepListening {
        handleUDPConnection(conn)
    }
}()
//notify the user that the server is listening
fmt.Sprintf("UDP server up and listening on port %s\n", port)
//run the server (I assume this function call is blocking
server.Run()
//stop the go routine when the server is done running
keepListening = false

希望对您有所帮助!

*协程不是线程。这么想可以是useful/simple,但它们是截然不同的。 Here's an article 解释一些差异和优点。