0

I'm trying to hack together a simple WebSocket client using tungstenite that parses JSON. Most of the code comes from this example.

If I do println!("{}", msg) It works fine, so I'm not sure why the type is mismatched (msg is supposedly a string right?). https://docs.rs/tungstenite/0.6.1/tungstenite/protocol/enum.Message.html

use tungstenite::{connect};
use url::Url;
use serde_json;

fn main() {

    let (mut socket, _response) =
        connect(Url::parse("wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD").unwrap()).expect("Can't connect");

    loop {
        let msg = socket.read_message().expect("Error reading message");
        let parsed: serde_json::Value = serde_json::from_str(&msg).expect("Can't parse to JSON");
        println!("{:?}", parsed["data"][0]["price"]);
    }

}
error[E0308]: mismatched types
  --> src/main.rs:12:62
   |
12 |         let parsed: serde_json::Value = serde_json::from_str(&msg).expect("Can't parse to JSON");
   |                                                              ^^^^ expected `str`, found enum `tungstenite::protocol::message::Message`
   |
   = note: expected reference `&str`
              found reference `&tungstenite::protocol::message::Message`
[dependencies]
tungstenite = "0.10.1"
url = "2.1.1"
serde_json = "1.0.53"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
SoGoddamnUgly
  • 706
  • 4
  • 9
  • *msg is supposedly a string* — [How do I print the type of a variable in Rust?](https://stackoverflow.com/q/21747136/155423) – Shepmaster May 26 '20 at 14:41
  • 2
    You can `println!("{}", msg)` because [`tungstenite::Message`](https://docs.rs/tungstenite/0.10.1/tungstenite/enum.Message.html) implements `Display`. See the documentation on how to turn it into a string. – E_net4 May 26 '20 at 14:46

1 Answers1

2

Something like this will work:

use tungstenite::{connect};
use url::Url;
use serde_json;

fn main() {

    let (mut socket, _response) =
        connect(Url::parse("wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD").unwrap()).expect("Can't connect");

    loop {
        let msg = socket.read_message().expect("Error reading message");
        let msg = match msg {
            tungstenite::Message::Text(s) => { s }
            _ => { panic!() }
        };
        let parsed: serde_json::Value = serde_json::from_str(&msg).expect("Can't parse to JSON");
        println!("{:?}", parsed["data"][0]["price"]);
    }

}

Jeff Muizelaar
  • 574
  • 2
  • 8
  • That works! I tried using to_text() / into_text() from here https://docs.rs/tungstenite/0.6.1/tungstenite/protocol/enum.Message.html any idea why that doesnt work? Anyways thanks! – SoGoddamnUgly May 27 '20 at 00:41