我正在尝试使用UDP服务器连续监听数据报和http服务器,但是从未达到字符串“UDP server up 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()
}
我怎样才能让它发挥作用?
答案 0 :(得分: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不是一个帖子。像这样思考它可能是有用/简单的,但它们明显不同。 Here's an article解释了一些差异和优势。