go - Golang: Mixing Gin with an UDP server -
i'm trying use both udp server listen continuously datagrams , http server, string "udp server , listening on port..." , command "server.run()" 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 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"}) }) { handleudpconnection(conn) } fmt.sprintf("udp server , listening on port %s\n", port) server.run() }
how can make work?
there infinite loop in code.
for { handleudpconnection(conn) }
this repetedly call handleudpconnection function until program exits without ever moving on to
fmt.sprintf("udp server , listening on port %s\n", port) server.run()
perhaps want deal connections in go thread. more this:
//define exit variable keeplistening := true //spawn go routine (starts function on thread*) go func() { keeplistening { handleudpconnection(conn) } }() //notify user server listening fmt.sprintf("udp server , listening on port %s\n", port) //run server (i assume function call blocking server.run() //stop go routine when server done running keeplistening = false
hope helps!
*a goroutine not thread. can useful/simple think of that, distinctly different. here's article explaining of differences , advantages.
Comments
Post a Comment