英文:
http.ServeFile and http.ServeContent cannot handle multiple clients
问题
场景:
我使用golang创建了一个简单的视频流媒体服务器。起初,我使用http.ServeContent
来提供视频内容。在我同时连接4个选项卡到服务器时,前两个选项卡可以正常工作,但是其他选项卡无法加载。我可以在播放两个视频的同时导航到菜单,但是其他选项卡无法播放视频。我还尝试了在多个设备上进行测试,只有两个连接可以播放视频。
因此,我将http.ServeContent
更改为http.ServeFile
,但问题仍然存在。当我使用io.Pipes
时,它可以处理每个请求,但问题是它无法进行定位。
以下是我的代码:
package main
import (
"log"
"net"
"net/http"
"github.com/gorilla/mux"
)
func serveVideo(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
title := vars["title"]
ep := vars["ep"]
http.ServeFile(w, r, "video/"+title+"/"+ep+".mp4")
}
func main() {
const port string = "8080"
// 创建mux路由器
r := mux.NewRouter()
r.HandleFunc("/video/{title}/{ep}", serveVideo)
// 让mux处理
http.Handle("/", r)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
希望这可以帮到你。谢谢。
英文:
Scenario <br>
I created a simple video streamer using golang. At First, I used http.ServeContent
to serve my videos. It was working until I simultaneously connected 4 tabs to my server but the first two only works and the rest aren't loading at all. I can navigate to the menu while streaming the two videos but I can't stream on the rest. I also tried it using multiple devices. Only two connections can stream.
So, I changed http.ServeContent
to http.ServeFile
but its still the same but when I used io.Pipes
, It served every request but the problem is that It can't seek.
Here is my code:
package main
import (
"log"
"net"
"net/http"
"github.com/gorilla/mux"
)
func serveVideo(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
title := vars["title"]
ep := vars["ep"]
http.ServeFile(w, r, "video/" + title + "/" ep + ".mp4")
}
func main() {
const port string = "8080"
// Create mux router
r := mux.NewRouter()
r.HandleFunc("/video/{title}/{ep}", serveVideo)
// let mux handle
http.Handle("/", r)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
I wish you could help. Thank you.
答案1
得分: 1
我怀疑你的代码没问题。所有主要的浏览器通常会限制与主机的并行活动连接数。
作为一个简单的测试,尝试使用类似于 curl
的工具多次进行流式传输,以确认你的代码是否真的存在问题。或者,尝试同时运行不同的浏览器(例如,在Chrome中打开2个标签,在Firefox中打开2个标签等)。
英文:
I suspect your code is fine. All major browsers will normally limit the number of parallel active connections to a host.
As a simple test, try streaming multiple times with something like curl
to confirm there is actually a problem with your code. Alternatively, try running different browsers simultaneously (e.g. 2 tabs in Chrome, 2 tabs in Firefox etc)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论