1

我正在尝试同时使用 UDP 服务器来连续监听数据报和 http 服务器,但是字符串“UDP 服务器启动并监听端口...”和命令“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()
}

我怎样才能让它工作?

4

1 回答 1

1

您的代码中有一个无限循环。

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

希望这可以帮助!

*goroutine 不是线程。这样想可能有用/简单,但它们明显不同。这是一篇文章,解释了一些差异和优势。

于 2016-05-28T20:40:05.753 回答