英文:
Serve a mp3 file with golang through websocket
问题
我想用Golang从WebSocket连接中提供一个文件。我可以像这样发送文件吗:
{type:"file_manage",information:"file.mp3"}?
英文:
I want to serve a file from an websocket connection with golang.
can i send the file like this:
{type:"file_manage",information:"file.mp3"} ?
答案1
得分: 1
只需读取文件并通过 WebSocket 发送。
package main
import (
"fmt"
"net/http"
"os"
"golang.org/x/net/websocket"
)
func EchoServer(ws *websocket.Conn) {
file, _ := os.ReadFile("a.txt")
n, err := ws.Write(file)
if err != nil {
fmt.Println(err)
}
fmt.Println(n, "字节已写入")
}
func main() {
http.Handle("/ws", websocket.Handler(EchoServer))
err := http.ListenAndServe(":12345", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
英文:
Just read file, and send by websocket.
package main
import (
"fmt"
"net/http"
"os"
"golang.org/x/net/websocket"
)
func EchoServer(ws *websocket.Conn) {
file, _ := os.ReadFile("a.txt")
n, err := ws.Write(file)
if err != nil {
fmt.Println(err)
}
fmt.Println(n, "bytes written")
}
func main() {
http.Handle("/ws", websocket.Handler(EchoServer))
err := http.ListenAndServe(":12345", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论