Serve a mp3 file with golang through websocket

huangapple go评论85阅读模式
英文:

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())
	}
}

huangapple
  • 本文由 发表于 2021年7月31日 10:19:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/68598594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定