我有一个问题,我想知道如何使用StreamReader读取WebSocket响应?
//WebSocket
WebSocket ws = new WebSocket("wss://stream.binance.com:9443/api/v3/userDataStream");
ws.Connect();
这样做:https://github.com/binance/binance-spot-api-docs/blob/master/user-data-stream.md#create-a-listenkey
我提前感谢
我发现了一些用StreamReader
从WebSocket
接收数据的示例。
public async Task<string> Receive()
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);//ToDo built in CancellationToken
if (result.MessageType == WebSocketMessageType.Close)
{
return "abort";
}
using (MemoryStream stream = new MemoryStream())
{
stream.Write(buffer,0, result.Count);
while(!result.EndOfMessage)
{
result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);//ToDo built in CancellationToken
stream.Write(buffer, 0, result.Count);
}
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string message = reader.ReadToEnd();
return message;
}
}
}
以下是此代码示例的网站链接:https://mycsharp.de/forum/threads/122437/websocket-client-beispiel
还有另一个从websocket读写的例子:https://thecodegarden.net/websocket-client-dotnet
我希望这能帮助你解决你的问题。