亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 Golang 中的服務器發送 websocket

如何從 Golang 中的服務器發送 websocket

Go
慕哥9229398 2022-05-10 17:12:26
我正在嘗試使用 Go 構建一個 websocket 應用程序,其中用戶輸入任何字符串,websocket 將字符串顯示回客戶端(瀏覽器)。但我需要另一個可以向 websocket 發送消息并在瀏覽器中顯示的 api (POST)。我試圖從類似的案例中學習,例如如何將消息從 golang 的 websocket 服務器主動發送到客戶端,但仍然無法將其關閉。請幫我。服務器(main.go)package mainimport (    "fmt"    "io/ioutil"    "net/http"    "github.com/gorilla/websocket")type msg struct {    Input string}func main() {    http.HandleFunc("/ws", wsHandler)    http.HandleFunc("/", rootHandler)    panic(http.ListenAndServe(":8080", nil))}func rootHandler(w http.ResponseWriter, r *http.Request) {    content, err := ioutil.ReadFile("index.html")    if err != nil {        fmt.Println("Could not open file.", err)    }    fmt.Fprintf(w, "%s", content)}func wsHandler(w http.ResponseWriter, r *http.Request) {    if r.Header.Get("Origin") != "http://"+r.Host {        http.Error(w, "Origin not allowed", 403)        return    }    conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)    if err != nil {        http.Error(w, "Could not open websocket connection", http.StatusBadRequest)    }    go echo(conn)}func echo(conn *websocket.Conn) {    for {        m := msg{}        err := conn.ReadJSON(&m)        if err != nil {            fmt.Println("Error reading json.", err)        }        fmt.Printf("Got message: %#v\n", m)        if err = conn.WriteJSON(m); err != nil {            fmt.Println(err)        }    }}
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

刪除 echo 函數前面的“go”,無需將其作為 goroutine 運行。當你這樣做時,它會立即關閉你的 Websocket 連接。我剛剛對此進行了測試,沒有它它可以正常工作



查看完整回答
反對 回復 2022-05-10
  • 1 回答
  • 0 關注
  • 275 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號