Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to read data from Websockets

Tags:

websocket

go

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])
    }
}
like image 538
continuousqa Avatar asked Sep 05 '17 21:09

continuousqa


People also ask

How do you interact with WebSockets?

In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.

Do WebSockets use alot of data?

Once established, a websocket connection does not have to send headers with its messages so we can expect the total data transfer per message to be less than an equivalent HTTP request. Establishing a Socket.io connection takes 1 HTTP request (~230 bytes) and one 86 byte websocket frame.

When should you not use a WebSocket?

You might be using WebSockets incorrectly if: The connection is used only for a very small number of events, or a very small amount of time, and the client does not need to quickly react to the events. Your feature requires multiple WebSockets to be open to the same service at once.

What is better than WebSocket?

SSE is best used when it's not necessary to send data from client to server. For example, in status updates and push notification applications, the data flow is from the server to the client only. This is what SSE is designed for, so WebSocket would be overkill.


1 Answers

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)
      }
    ...
like image 99
Shmulik Klein Avatar answered Sep 30 '22 08:09

Shmulik Klein