我想从这个wss获取数据://ws-feed.gdax.com
我对websocket一无所知。我正在阅读一些教程,它使用websocket服务器,TCP等术语,我不知道。任何人都可以建议我该如何处理,如何编写一个c#代码来从上面获取数据。
这是我读取的用于获取实时数据的文档 - https://docs.gdax.com/#websocket-feed
通过创建窗口应用程序启动。在这里读到WebSocketSharp库可用于连接WebSockets,因此安装它并到目前为止编写了这段代码:
using (var ws = new WebSocket("wss://ws-feed.gdax.com"))
{
ws.Connect();
string json = "{\"type\": \"subscribe\", \"product_ids\": [\"BTC-USD\"]}";
ws.Send(json); //gives error -Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
}
非常感谢任何帮助。
答案 0 :(得分:5)
ClientWebSocket socket = new ClientWebSocket();
Task task = socket.ConnectAsync(new Uri("wss://ws-feed.gdax.com"), CancellationToken.None);
task.Wait();
Thread readThread = new Thread(
delegate(object obj)
{
byte[] recBytes = new byte[1024];
while (true) {
ArraySegment<byte> t = new ArraySegment<byte>(recBytes);
Task<WebSocketReceiveResult> receiveAsync = socket.ReceiveAsync(t, CancellationToken.None);
receiveAsync.Wait();
string jsonString = Encoding.UTF8.GetString(recBytes);
Console.Out.WriteLine("jsonString = {0}", jsonString);
recBytes = new byte[1024];
}
});
readThread.Start();
string json = "{\"product_ids\":[\"btc-usd\"],\"type\":\"subscribe\"}";
byte[] bytes = Encoding.UTF8.GetBytes(json);
ArraySegment<byte> subscriptionMessageBuffer = new ArraySegment<byte>(bytes);
socket.SendAsync(subscriptionMessageBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
Console.ReadLine();
答案 1 :(得分:0)
基本上,你所做的是朝着正确的方向发展。在阅读消息之前,请检查websocket状态。
以下示例来自https://github.com/sefbkn/gdax.netcore,几乎没有修改
var webSocketClient = new ClientWebSocket();
var cancellationToken = new CancellationToken();
await webSocketClient.ConnectAsync(new Uri("wss://ws-feed.gdax.com"), cancellationToken).ConfigureAwait(false);
if (webSocketClient.State == WebSocketState.Open)
{
var requestString = JsonConvert.SerializeObject(new {
type = "subscribe",
product_ids = new[]{"ETH-EUR"},
channels = new[]{"ticker"}
});
var requestBytes = UTF8Encoding.UTF8.GetBytes(requestString);
var subscribeRequest = new ArraySegment<byte>(requestBytes);
var sendCancellationToken = new CancellationToken();
await webSocketClient.SendAsync(subscribeRequest, WebSocketMessageType.Text, true, sendCancellationToken).ConfigureAwait(false);
while (webSocketClient.State == WebSocketState.Open)
{
var receiveCancellationToken = new CancellationToken();
using(var stream = new MemoryStream(1024))
{
var receiveBuffer = new ArraySegment<byte>(new byte[1024*8]);
WebSocketReceiveResult webSocketReceiveResult;
do
{
webSocketReceiveResult = await webSocketClient.ReceiveAsync(receiveBuffer, receiveCancellationToken).ConfigureAwait(false);
await stream.WriteAsync(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count);
} while(!webSocketReceiveResult.EndOfMessage);
var message = stream.ToArray().Where(b => b != 0).ToArray();
messageReceived(Encoding.ASCII.GetString(message, 0, message.Length));
}
}
}