C# WebSocket Error Authorization
Why i get authorization error ?
using System;
using System.Text;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.Threading;
using System.Net;
namespace BinaryWSDemo
{
class BinaryWS
{
private ClientWebSocket ws = new ClientWebSocket();
private Uri uri = new Uri("wss://ws.binaryws.com/websockets/v3?app_id=3562");
public ClientWebSocket Ws { get => Ws1; set => Ws1 = value; } public Uri Uri { get => Uri1; set => Uri1 = value; } public ClientWebSocket Ws1 { get => Ws2; set => Ws2 = value; } public Uri Uri1 { get => Uri2; set => Uri2 = value; } public ClientWebSocket Ws2 { get => ws; set => ws = value; } public Uri Uri2 { get => uri; set => uri = value; } public async Task SendRequest(string data) { while (this.Ws.State == WebSocketState.Connecting) { }; if (this.Ws.State != WebSocketState.Open) { throw new Exception("Connection is not open."); } var reqAsBytes = Encoding.UTF8.GetBytes(data); var ticksRequest = new ArraySegment<byte>(reqAsBytes); await this.Ws.SendAsync(ticksRequest, WebSocketMessageType.Text, true, CancellationToken.None); Console.WriteLine("The request has been sent: "); Console.WriteLine(data); Console.WriteLine("\r\n \r\n"); } public async Task StartListen() { WebSocketReceiveResult result; while (this.Ws.State == WebSocketState.Open) { var buffer = new ArraySegment<byte>(new byte[1024]); do { result = await this.Ws.ReceiveAsync(new ArraySegment<byte>(buffer.Array), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { Console.WriteLine("Connection Closed!"); break; } else { var str = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); Console.WriteLine("Received Data at: " + DateTime.Now); Console.WriteLine(str); Console.WriteLine("\r\n"); } } while (!result.EndOfMessage); } } public async Task Connect() { Console.WriteLine("Prepare to connect to: " + this.Uri.ToString()); Console.WriteLine("\r\n"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; await Ws.ConnectAsync(Uri, CancellationToken.None); Console.WriteLine("The connection is established!"); Console.WriteLine("\r\n"); } static void Main(string[] args) { string data = "{\"authorize\":\"as6gR2r13eqz4jm\"}"; string portfolio = "{\"portfolio\":\"1\"}"; var bws = new BinaryWS(); bws.Connect().Wait(); bws.SendRequest(data).Wait(); bws.SendRequest(portfolio).Wait(); bws.StartListen(); Console.ReadLine(); } }
}
Received Data at: 03/05/2017 00:48:35
{"echo_req":{"portfolio":"1"},"error":{"code":"AuthorizationRequired","message":"Please log in."},"msg_type":"portfolio"}
Comments
Please note that you need to call portfolio only when connection is authorized. So
bws.SendRequest(portfolio)
needs to called when you receive response ofbws.SendRequest(data)
so how i could do this ? Thank you.
@g97iulio so when you do this
check
this is just pseudo code to explain the logic
ok thank you.