为了账号安全,请及时绑定邮箱和手机立即绑定

来自websocket的Golang bufio在第一次阅读后中断

来自websocket的Golang bufio在第一次阅读后中断

Go
喵喔喔 2022-11-08 10:44:37
我正在尝试从 websocket 流式传输 JSON 文本。但是,在初次阅读后,我注意到流似乎中断/断开连接。这是来自 Pleroma 服务器(想想:Mastodon)。我正在使用默认的 Golang websocket 库。package mainimport (    "bufio"    "fmt"    "log"    "golang.org/x/net/websocket")func main() {    origin := "https://poa.st/"    url := "wss://poa.st/api/v1/streaming/?stream=public"    ws, err := websocket.Dial(url, "", origin)    if err != nil {        log.Fatal(err)    }    s := bufio.NewScanner(ws)    for s.Scan() {        line := s.Text()        fmt.Println(line)    }}在初始 JSON 文本响应之后,for 循环中断。我希望它每隔几秒钟发送一条新消息。这可能是什么原因造成的?如果我可以使用 Gorilla websocket 库,我愿意切换到bufio.谢谢!
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

尽管 x/net/websocket 连接具有与 io.Reader 中的 Read 方法具有相同签名的 Read 方法,但该连接不像 io.Reader 那样工作。使用 bufio.Scanner 包裹时,连接将无法正常工作。


poa.st 端点发送消息流,其中每条消息都是一个 JSON 文档。使用以下代码使用Gorilla 包读取消息:


url := "wss://poa.st/api/v1/streaming/?stream=public"

ws, _, err := websocket.DefaultDialer.Dial(url, nil)

if err != nil {

    log.Fatal(err)

}

defer ws.Close()


for {

    _, p, err := ws.ReadMessage()

    if err != nil {

        log.Fatal(err)

    }

    // p is a []byte containing the JSON document.

    fmt.Printf("%s\n", p)

}

Gorilla 包有一个用于解码 JSON 消息的辅助方法。这是一个如何使用该方法的示例。


url := "wss://poa.st/api/v1/streaming/?stream=public"

ws, _, err := websocket.DefaultDialer.Dial(url, nil)

if err != nil {

    log.Fatal(err)

}

defer ws.Close()


for {

    // The JSON documents are objects containing two fields, 

    // the event type and the payload. The payload is a JSON

    // document itself.

    var e struct {

        Event   string

        Payload string

    }


    err := ws.ReadJSON(&e)

    if err != nil {

        log.Fatal(err)

    }

    // TODO: decode e.Payload based on e.Event

}


查看完整回答
反对 回复 2022-11-08
  • 1 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号