douhe1864 2016-05-28 12:25
浏览 602
已采纳

Golang:将Gin与UDP服务器混合

I'm trying to use both a UDP server to listen continuously to datagrams and a http server, but the string "UDP server up and listening on port..." and command "server.Run()" are never reached.

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
", port)
    server.Run()
}

How can I make it work?

  • 写回答

1条回答 默认 最新

  • doujiushi9007 2016-05-28 20:40
    关注

    There is an infinite loop in your code.

    for {
        handleUDPConnection(conn)
    }
    

    This will repetedly call the handleUDPConnection function until the program exits without ever moving on to

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

    Perhaps you want to deal with the connections in a go thread. This would be something more like this:

    //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
    ", 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
    

    Hope this helps!

    *a goroutine is not a thread. It can be useful/simple to think of it like that, but they are distinctly different. Here's an article explaining some of the differences and advantages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型