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.

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

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧