从Websockets读取数据的最佳方法

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

Best way to read data from Websockets

问题

我正在学习Go(Golang),并有一个项目的想法。该项目将是一个Web应用程序,从第三方WebSocket获取数据流。目前,我正在尝试让我的Go项目读取WebSocket数据以便我可以解析它。

第三方WebSocket是一个JSON对象的数据流。

到目前为止,我已经成功地监听WebSocket。然而,我对如何处理它感到困惑。主要是,我在WebSocket库上使用的读取方法返回的是一个字节切片。这似乎很难转换为JSON对象。有没有更好的方法来读取WebSocket并收集JSON对象?

目标

我的目标是监听这个公共WebSocket,获取JSON对象,然后我可以解析其中我想要的字段,并将其传入一个视图(动态更新数据流)。

如果没有更好的方法,我该如何将字节切片转换回JSON对象?

代码

这是我的代码:

package main

import (
	"golang.org/x/net/websocket"
	"fmt"
	"log"
)

func main(){

	origin := "http://localhost/"
	url := "wss://ws-feed.gdax.com"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := ws.Write([]byte(`{"type":"subscribe", "product_ids":["LTC-USD"]}`)); err != nil {
		log.Fatal(err)
	}
	var msg = make([]byte, 512)
	var n int
	for 1>0{
		if n, err = ws.Read(msg); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Received: %s.\n", msg[:n])
	}
}
英文:

I'm learning Go (Golang) and had a project in mind. The project would be a web app that pulls in a data stream from a 3rd party websocket. At this point, I'm trying to get my Go project to read the web socket data so I can parse it.

The 3rd party websocket is a data stream of JSON objects.

So far I've been able to successfully listen to the websocket. However, I'm confused on how to best deal with this. Namely, the read method I'm using on the Websocket library is getting a slice of bytes. Which seems challenging to turn into JSON objects. Is there a better way to read the websocket - collecting the JSON objects?

Goal

My goal is to listen to this public web socket, get json objects - which I can parse for a field of my desire which would then be pulled into a view (dynamically updating with the data stream.)

If not, how can I convert the slice of bytes back to a JSON object?

Code

Here's my code:

    package main

import (
	"golang.org/x/net/websocket"
	"fmt"
	"log"
)

func main(){

	origin := "http://localhost/"
	url := "wss://ws-feed.gdax.com"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := ws.Write([]byte(`{"type":"subscribe", "product_ids":["LTC-USD"]}`)); err != nil {
		log.Fatal(err)
	}
	var msg = make([]byte, 512)
	var n int
	for 1>0{
		if n, err = ws.Read(msg); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Received: %s.\n", msg[:n])
	}
}

答案1

得分: 6

首先,不要使用websocket.Readwebsocket.Write来读取/写入websocket,最好使用方便的websocket.Message对象及其对应的websocket.Message.Receive()websocket.Message.Send()函数。这两个函数都用于以UTF-8编码的字符串或字节序列发送。

如果你期望在socket上发送JSON对象,最好使用websocket.JSON.Receive()而不是websocket.Message.Receive

使用方法如下:

...
type Person struct {
  Name string
  Emails []string
}

func ReceivePerson(ws *websocket.Conn) {
  var person Person
  err := websocket.JSON.Receive(ws, &person)
  if err != nil {
     log.Fatal(err)
  }
...
英文:

First, don't use websocket.Read and websocket.Write to read/write from/to a websocket - better use the convenience websocket.Message object and its corresponding websocket.Message.Receive() and websocket.Message.Send() functions. Both of them are used to send strings in UTF-8 encoding or a sequence of bytes.

If you are expecting JSON objects to be sent on the socket, you better use websocket.JSON.Receive() instead of websocket.Message.Receive.

Use it as follows:

    ...    
    type Person struct {
      Name string
      Emails []string
    }

    func ReceivePerson(ws *websocket.Conn) {
      var person Person
      err := websocket.JSON.Receive(ws, &person)
      if err != nil {
         log.Fatal(err)
      }
    ...

huangapple
  • 本文由 发表于 2017年9月6日 05:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/46063413.html
匿名

发表评论

匿名网友

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

确定