Websockets in R

2019-04-10 21:33发布

I managed to establish a connection in R to Mtgox websocket with following specs:

I used the improved R library "websocket" downloaded from https://github.com/zeenogee/R-Websockets:

require("websockets")
con = websocket("https://socketio.mtgox.com/mtgox?Currency=USD")

and the connection was successfully established. However, it seems that the socket is not broadcasting. I made an easy function f

  f = function(con) {
  Print("Test Test!", con)
}

set_callback("receive", f, con)

while(TRUE)
  {
  service(con)
  Sys.sleep(0.05)
  }

which should print some text whenever some data are received from the websocket. But the websocket doesnt seem to trigger the "receive" method and nothing is displayed. Code ended up with infinite loop with no output.

I know that the websocket is working so there must be a mistake in the code. Do I have to "ping" the socket somehow to start broadcasting? Anyone has anidea how to get it working? Thanks!

1条回答
Luminary・发光体
2楼-- · 2019-04-10 21:39

Firstly, you have an infinite loop, because you have defined an infinite loop:

While(TRUE)

It is worth noting, numerous R websocket implementations leverage this loop, so may not be a bug but rather an implementation detail causing what you are seeing.

It would appear that you need to subscribe to the 'message' event not 'receive' ( https://en.bitcoin.it/wiki/MtGox/API/Streaming).

In JavaScript (from MtGox Spec):

conn.on('message', function(data) {
    // Handle incoming data object.
});

Or in R:

set_callback('message',f,con)

Failing that...

I would also comment to say, that maybe the stream is returning you data that you are not able to implicitly print in R Print function.

Sample:

{
  "op":"remark",
  "message":<MESSAGE FROM THE SERVER>,
  "success":<boolean>
}

If the data follows this format as defined in spec, you may which to examine how that data is being parsed, and the "op" which is being returned.

查看更多
登录 后发表回答