我正在实现一个服务器来流式传输许多浮点数数组。我需要一些帮助来设计我的系统以实现以下目标:
音频进程必须是独立的,即使没有任何请求进来也能完成它的工作。我目前的方法使 DataProcess 函数等待直到有请求。
因为通道只能给1个请求提供数据,2个以上的请求怎么才能拿到我在DataProcess中准备好的数据呢?
为了实际流式传输数据,请求处理程序不能等待整个 DataProcess 完成,无论如何,一旦我们完成 DataProcess 中的每个迭代,就给处理程序数据?
任何答复表示赞赏。这是我目前的想法:
package main
import (
"fmt"
"io"
"net/http"
"strconv"
"time"
)
func main() {
c := AudioProcess()
handleHello := makeHello(c)
http.HandleFunc("/", handleHello)
http.ListenAndServe(":8000", nil)
}
func makeHello(c chan string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
for item := range c { // this loop runs when channel c is closed
io.WriteString(w, item)
}
}
}
func AudioProcess() chan string {
c := make(chan string)
go func() {
for i := 0; i <= 10; i++ { // Iterate the audio file
c <- strconv.Itoa(i) // have my frame of samples, send to channel c
time.Sleep(time.Second)
fmt.Println("send ", i) // logging
}
close(c) // done processing, close channel c
}()
return c
}
偶然的你
相关分类