http - 是否可以同时运行 http.ListenAndServe() AND ReadFromUDP() ?

标签 http go udp

我正在尝试编写一个简单的 Web 应用程序来监听 UDP 数据包。

但我要么只能监听 UDP 数据包,要么运行网络应用程序......
我不熟悉 GoLang,但这是我用来...
监听 UDP:

 ServerConn, _ := net.ListenUDP("udp", &net.UDPAddr{IP:[]byte{#,#,#,#},Port:####,Zone:""})
  defer ServerConn.Close()
  buf := make([]byte, 1024)

  for {
    n, addr, _ := ServerConn.ReadFromUDP(buf)
    fmt.Println("Received ", string(buf[0:n]), " from ", addr)
  }

服务器逻辑:
    package main
We import 4 important libraries 
1. “net/http” to access the core go http functionality
2. “fmt” for formatting our text
3. “html/template” a library that allows us to interact with our html file.
4. "time" - a library for working with date and time.
import (
   "net/http"
   "fmt"
   "time"
   "html/template"
)

//Create a struct that holds information to be displayed in our HTML file
type Welcome struct {
   Name string
   Time string
}

//Go application entrypoint
func main() {
   //Instantiate a Welcome struct object and pass in some random information. 
   //We shall get the name of the user as a query parameter from the URL
   welcome := Welcome{"Anonymous", time.Now().Format(time.Stamp)}

   //We tell Go exactly where we can find our html file. We ask Go to parse the html file (Notice
   // the relative path). We wrap it in a call to template.Must() which handles any errors and halts if there are fatal errors

   templates := template.Must(template.ParseFiles("templates/welcome-template.html"))

   //Our HTML comes with CSS that go needs to provide when we run the app. Here we tell go to create
   // a handle that looks in the static directory, go then uses the "/static/" as a url that our
   //html can refer to when looking for our css and other files. 

   http.Handle("/static/", //final url can be anything
      http.StripPrefix("/static/",
         http.FileServer(http.Dir("static")))) //Go looks in the relative "static" directory first using http.FileServer(), then matches it to a
         //url of our choice as shown in http.Handle("/static/"). This url is what we need when referencing our css files
         //once the server begins. Our html code would therefore be <link rel="stylesheet"  href="/static/stylesheet/...">
         //It is important to note the url in http.Handle can be whatever we like, so long as we are consistent.

   //This method takes in the URL path "/" and a function that takes in a response writer, and a http request.
   http.HandleFunc("/" , func(w http.ResponseWriter, r *http.Request) {

      //Takes the name from the URL query e.g ?name=Martin, will set welcome.Name = Martin.
      if name := r.FormValue("name"); name != "" {
         welcome.Name = name;
      }
      //If errors show an internal server error message
      //I also pass the welcome struct to the welcome-template.html file.
      if err := templates.ExecuteTemplate(w, "welcome-template.html", welcome); err != nil {
         http.Error(w, err.Error(), http.StatusInternalServerError)
      }
   })

   //Start the web server, set the port to listen to 8080. Without a path it assumes localhost
   //Print any errors from starting the webserver using fmt
   fmt.Println("Listening");
   fmt.Println(http.ListenAndServe(":8080", nil));
}

取自(https://medium.com/google-cloud/building-a-go-web-app-from-scratch-to-deploying-on-google-cloud-part-1-building-a-simple-go-aee452a2e654)

我尝试将这两个提取物放在 1 个文件中,并使用同时运行 2 个文件
go run *.go

任何帮助,将不胜感激!

最佳答案

您将需要开始研究 goroutines - 因为您要求同时做两件事。我建议对 channel 、goroutines 和一般并发进行一些阅读:)

关于http - 是否可以同时运行 http.ListenAndServe() AND ReadFromUDP() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356709/

相关文章:

json - 如何将来自 HTTP Get 请求的数据存储在结构体 slice 中

go - 在 Go 中获取系统文件夹路径?

python - Python 中的用户身份验证和文本解析

python - 使用Python登录ask.fm

database - 如何编写与数据库无关的函数以使其更易于单元测试

c - Sendto:参数无效错误

objective-c - 使用 "struct sflt_filter"为 TCP 和 UDP 协议(protocol)设置数据过滤器

Python UDP recvfrom()具体地址

http - Golang 在等待数据加载时显示静态 HTML 模板

python - Python 中使用 JSON 数据的 HTTP PUT 请求