Beispiel #1
0
        public static void Main(string[] args)
        {
            _timer = new Timer(OnTick, null, 2000, 1);

RESTART:
            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode           = true,
                SendDelay           = 100,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            };

            _ws = new PureWebSocket("wss://echo.websocket.org", socketOptions);

            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            _ws.Connect();

            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
Beispiel #2
0
        private static void Program_OnOpened(object sender)
        {
            PureWebSocket ws = sender as PureWebSocket;
            Console.WriteLine($@"{ws.InstanceName}: Opened");

            Send(ws, $"1\t{Interlocked.Increment(ref UserId)}\tmewow");
        }
Beispiel #3
0
        public static async Task Main(string[] args)
        {
            // this is just a timer to send data for us (simulate activity)
            _timer = new Timer(OnTickAsync, null, 4000, 1);

RESTART:
            var socketOptions = new PureWebSocketOptions
            {
                DebugMode           = false,                                // set this to true to see a ton O' logging
                SendDelay           = 100,                                  // the delay in ms between sending messages
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20) // automatic reconnect if connection is lost
            };

            _ws = new PureWebSocket("wss://demos.kaazing.com/echo", socketOptions, "MyOptionalInstanceName1");

            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            await _ws.ConnectAsync();

            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
Beispiel #4
0
        public async void Start()
        {
            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode           = false,
                SendDelay           = 100,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            };

            ws = new PureWebSocket("ws://" + _url + "/websocket", socketOptions);
            ws.OnStateChanged += Ws_OnStateChanged;
            ws.OnMessage      += Ws_OnMessage;
            ws.OnClosed       += Ws_OnClosed;
            ws.OnSendFailed   += Ws_OnSendFailed;
            await ws.ConnectAsync();

            Console.WriteLine("SENDING WEBSOCKET MESSAGE");
            string[] s = new string[1];
            s[0] = "1";
            WebSocket.ConnectMsg c = new WebSocket.ConnectMsg()
            {
                msg     = "connect",
                version = "1",
                support = s
            };

            await ws.SendAsync(JsonConvert.SerializeObject(c));

            Console.ReadLine();
            ws.Dispose(true);

            await ws.ConnectAsync();
        }
Beispiel #5
0
        /// <summary>
        ///     Connect to the server and start processing messages
        /// </summary>
        public void Connect()
        {
            _webSocket?.Dispose();

            _disconnectCalled = false;

            // get the connection info from the signalr host
            var connInf = SignalR.Negotiate(_httpHost, _hubs);

            // we only work with websockets
            if (!connInf.TryWebSockets)
            {
                throw new WebSocketException(WebSocketError.UnsupportedProtocol,
                                             "WebSocket Connections Not Supported By This Host");
            }

            _connectionToken = connInf.ConnectionToken;
            _connectionId    = connInf.ConnectionId;

            _webSocket = SignalR.Connect(_wsHost, _connectionToken, _hubs);

            HookupEvents();

            _webSocket.Connect();

            if (Debug)
            {
                WriteLine($"Connect Called, URL: {_rootHost}");
            }
        }
Beispiel #6
0
        public void Connect()
        {
            if (IsConnected())
            {
                return;
            }

            Disconnect(() =>
            {
                var opts = new PureWebSocketOptions
                {
                    MyReconnectStrategy = new ReconnectStrategy(1000, 30000)
                };
                _conn            = new PureWebSocket(_endPoint, opts);
                _conn.OnOpened  += OnConnOpen;
                _conn.OnError   += OnConnError;
                _conn.OnMessage += OnConnMessage;
                _conn.OnClosed  += OnConnClose;
                try
                {
                    _conn.Connect();
                    _reconnectTimer.Stop();
                }
                catch (Exception ex)
                {
                    _reconnectTimer.Start();
                }
            });
        }
Beispiel #7
0
        /// <summary>
        /// State used while trying to connect.
        /// </summary>
        private void Connecting()
        {
            Log.Information("State::Connecting.");

            Receive <Socket_Connected>(msg => Become(Subscribed));
            Receive <Socket_Disconnected>(msg => Become(Disconnected));

            Log.Information("Starting connection to {0}.", _url);

            // start connecting
            _socket = new PureWebSocket(
                _url,
                new PureWebSocketOptions
            {
                SendDelay = 100,
                DebugMode = false
            });

            _socket.OnStateChanged += Socket_OnStateChanged(Self);
            _socket.OnMessage      += Socket_OnMessage(_subscriber);
            _socket.OnClosed       += Socket_OnClosed(Self);

            try
            {
                _socket.Connect();
            }
            catch
            {
                // socket close handler will be called
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            PureWebSocket[] socks = new PureWebSocket[100];

            for(int i = 0; i < socks.Length; i++)
            {
                socks[i] = new PureWebSocket(@"ws://127.0.0.1:6770/", new PureWebSocketOptions { });
                socks[i].OnOpened += Program_OnOpened;
                socks[i].OnClosed += Program_OnClosed;
                socks[i].OnSendFailed += Program_OnSendFailed;
                socks[i].OnStateChanged += Program_OnStateChanged;
                socks[i].OnError += Program_OnError;
                socks[i].OnFatality += Program_OnFatality;
                socks[i].OnMessage += Program_OnMessage;
                socks[i].OnData += Program_OnData;
            }

            Parallel.ForEach(socks, sock => sock.Connect());

            string msg;
            while ((msg = Console.ReadLine()) != @";q")
            {
                string pack = $"2\t0\t{msg}";
                Parallel.ForEach(socks, sock => Send(sock, pack));
            }

            while(!Parallel.ForEach(socks, sock => sock.Dispose()).IsCompleted);

            Console.ReadLine();
        }
Beispiel #9
0
        public HubitatClient(HubitatOptions options, ILogger logger)
        {
            _options = options;
            _logger  = logger;

            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode           = true,
                SendDelay           = 100,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(options.MinReconnectInterval, options.MaxReconnectInterval, options.MaxReconnectAttempts)
            };

            _webSocket                 = new PureWebSocket(_options.WebSocketURL, socketOptions);
            _webSocket.OnOpened       += (sender) => SocketOpen();
            _webSocket.OnStateChanged += (sender, newState, previousState) => SocketStateChanged(newState, previousState);
            _webSocket.OnMessage      += (sender, message) => MessageReceived(message);
            _webSocket.OnClosed       += (sender, reason) => SocketClosed(reason);
            _webSocket.OnSendFailed   += (sender, data, ex) => SocketSendFailed(data, ex);
            _webSocket.OnError        += (sender, e) => SocketError(e);

            _collector = Metrics.Collector = new CollectorConfiguration()
                                             .Batch.AtInterval(TimeSpan.FromSeconds(options.BatchInterval))
                                             .WriteTo.InfluxDB(options.InfluxDbURL, options.InfluxDbDatabase, options.InfluxDbUsername, options.InfluxDbPassword)
                                             .CreateCollector();

            CollectorLog.RegisterErrorHandler((string message, Exception ex) =>
            {
                _logger.Error(ex, "Failed to write metrics to InfluxDB: {Message}", message);
            });
        }
Beispiel #10
0
        public static async Task Main(string[] args)
        {
            _timer = new Timer(OnTickAsync, null, 2000, 1);

RESTART:
            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode           = true,
                SendDelay           = 100,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(3000, 6000)
            };

            _ws = new PureWebSocket("wss://demos.kaazing.com/echo", socketOptions);

            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            try
            {
                await _ws.ConnectAsync();
            }
            catch (Exception e) {
                _ws.Dispose();
                goto RESTART;
            }


            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
Beispiel #11
0
        public PureSocketClusterSocket(string url, PureSocketClusterOptions options, string instanceName)
        {
            _options = options;

            if (_options.DebugMode)
            {
                Log("WARNING: Debug logging is enabled, sensitive data may be disclosed!");
            }

            Log("Creating new instance.");

            if (options.Serializer is null)
            {
                options.Serializer = new Utf8JsonSerializer();
            }

            _counter = 0;

            Channels = new List <Channel>();

            _acks = new Dictionary <long?, object[]>();

            _socket = new PureWebSocket(url, options, instanceName);

            SetupEvents();
        }
        /// <summary>
        /// Disconnect the WebSocket and dispose the objects involved
        /// </summary>
        public void DisconnectAndDispose()
        {
            logger.LogInformation("DisconnectAndDispose() is being called");
            PureWebSocket pureWebSocket = new PureWebSocket(webSocketConfiguration.FullUrl, socketOptions);

            pureWebSocket?.Disconnect();
            pureWebSocket?.Dispose();
        }
Beispiel #13
0
        internal static int InvokeHubMethod(PureWebSocket socket, string hubName, string methodName, ISerializer serializer, params object[] parameters)
        {
            // Transport: ws
            // example which should not be encoded before sending
            // {"H":"chatHub","M":"getOnlineCount","A":[],"I":319104157}
            var msgId = int.Parse(DateTime.Now.ToString("MMddhhmmss"));
            var sb    = new StringBuilder();

            sb.Append("{\"H\":\"").Append(hubName).Append("\",\"M\":\"").Append(methodName).Append("\",\"A\":[");
            if (parameters.Length > 0)
            {
                for (var i = 0; i < parameters.Length; i++)
                {
                    switch (parameters[i])
                    {
                    case short _:
                    case int _:
                    case long _:
                    case ushort _:
                    case uint _:
                    case ulong _:
                    case double _:
                    case decimal _:
                    case float _:
                        sb.Append(parameters[i]);
                        break;

                    case bool _ when(bool) parameters[i]:
                        sb.Append(1);

                        break;

                    case bool _:
                        sb.Append(0);
                        break;

                    case string _:
                        sb.Append("\"").Append(parameters[i]).Append("\"");
                        break;

                    default:
                        sb.Append(serializer.Serialize(parameters[i]));
                        break;
                    }

                    if (i < parameters.Length - 1)
                    {
                        sb.Append(",");
                    }
                }
            }
            sb.Append("],\"I\":").Append(msgId).Append("}");
            if (socket.Send(sb.ToString()))
            {
                return(msgId);
            }
            return(-1);
        }
Beispiel #14
0
        internal bool Connect()
        {
            _websocket             = new PureWebSocket(_url, _purePusherClient.Options);
            _websocket.OnOpened   += _websocket_OnOpened;
            _websocket.OnError    += _websocket_OnError;
            _websocket.OnClosed   += _websocket_OnClosed;
            _websocket.OnFatality += _websocket_OnFatality;
            _websocket.OnMessage  += _websocket_OnMessage;

            return(_websocket.Connect());
        }
Beispiel #15
0
        public void Init()
        {
            _socket = new PureWebSocket(options.Url, _options);

            _socket.OnStateChanged += _socket_OnStateChanged;
            _socket.OnMessage      += _socket_OnMessage;
            _socket.OnClosed       += _socket_OnClosed;
            _socket.OnSendFailed   += _socket_OnSendFailed;
            _socket.OnOpened       += _socket_OnOpened;
            _socket.OnError        += _socket_OnError;
        }
        /// <summary>
        /// Connect the WebSocket and register all the events
        /// </summary>
        /// <returns>true if the connection was successful, false otherwise</returns>
        public async Task <bool> ConnectAndRegisterAsync()
        {
            logger.LogInformation("ConnectAndRegisterAsync() is working.");
            PureWebSocket pureWebSocket = new PureWebSocket(webSocketConfiguration.FullUrl, socketOptions);

            pureWebSocket.OnStateChanged += WSOnStateChanged;
            pureWebSocket.OnMessage      += WSOnMessage;
            pureWebSocket.OnOpened       += WSOnOpened;
            pureWebSocket.OnError        += WSOnError;
            logger.LogDebug("ConnectAndRegisterAsync() All custom events registered");
            return(await pureWebSocket.ConnectAsync());
        }
Beispiel #17
0
        public void Connect(string url)
        {
            ws = new PureWebSocket(url, new ReconnectStrategy(10000, 60000));

            ws.OnMessage      += OnMessage;
            ws.OnSendFailed   += OnSendFailed;
            ws.OnError        += OnError;
            ws.OnClosed       += OnClosed;
            ws.OnStateChanged += OnStateChanged;
            ws.OnOpened       += Ws_OnOpened;

            ws.Connect();
        }
Beispiel #18
0
 public void Close()
 {
     if (_socket != null && _socket.State == WebSocketState.Open)
     {
         _socket.OnStateChanged -= _socket_OnStateChanged;
         _socket.OnMessage      -= _socket_OnMessage;
         _socket.OnClosed       -= _socket_OnClosed;
         _socket.OnSendFailed   -= _socket_OnSendFailed;
         _socket.OnOpened       -= _socket_OnOpened;
         _socket.OnError        -= _socket_OnError;
         _socket.Dispose(true);
         _socket = null;
     }
 }
        /// <summary>
        /// Connects to a UserData Websocket endpoint.
        /// </summary>
        /// <param name="parameters">Paremeters to send to the Websocket.</param>
        /// <param name="accountHandler">Deletage to callback after receive a account info message.</param>
        /// <param name="tradeHandler">Deletage to callback after receive a trade message.</param>
        /// <param name="orderHandler">Deletage to callback after receive a order message.</param>
        public void ConnectToUserDataWebSocket(string parameters, MessageHandler <AccountUpdatedMessage> accountHandler, MessageHandler <OrderOrTradeUpdatedMessage> tradeHandler, MessageHandler <OrderOrTradeUpdatedMessage> orderHandler)
        {
            var finalEndpoint = _webSocketEndpoint + parameters;

            var ws = new PureWebSocket(finalEndpoint, new PureWebSocketOptions()
            {
                DebugMode           = false,//true,
                SendDelay           = 10,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            });

            ws.OnMessage += (data) =>
            {
                var eventData = JsonConvert.DeserializeObject <dynamic>(data);

                switch (eventData.e)
                {
                case "outboundAccountInfo":
                    accountHandler(JsonConvert.DeserializeObject <AccountUpdatedMessage>(data));
                    break;

                case "executionReport":
                    var isTrade = ((string)eventData.x).ToLower() == "trade";

                    if (isTrade)
                    {
                        tradeHandler(JsonConvert.DeserializeObject <OrderOrTradeUpdatedMessage>(data));
                    }
                    else
                    {
                        orderHandler(JsonConvert.DeserializeObject <OrderOrTradeUpdatedMessage>(data));
                    }
                    break;
                }
            };

            ws.OnClosed += (reason) =>
            {
                _openSockets.Remove(ws);
            };

            ws.OnError += (error) =>
            {
                _openSockets.Remove(ws);
            };

            ws.Connect();
            _openSockets.Add(ws);
        }
Beispiel #20
0
        internal async Task <JsonZKill.Killmail> GetSocketResponce()
        {
            try
            {
                if (_webSocket == null || _webSocket.State != WebSocketState.Open)
                {
                    if (_webSocket?.State == WebSocketState.Connecting)
                    {
                        return(null);
                    }
                    var o = new PureWebSocketOptions();
                    _webSocket?.Dispose();
                    _webSocket            = new PureWebSocket(SettingsManager.Settings.Config.ZKillboardWebSocketUrl, o);
                    _webSocket.OnMessage += _webSocket_OnMessage;
                    _webSocket.OnError   += async exception => { await LogHelper.LogEx("_webSocket.OnError", exception, LogCat.ZKill); };

                    if (!_webSocket.Connect())
                    {
                        _webSocket?.Dispose();
                        _webSocket = null;
                        return(null);
                    }
                    else
                    {
                        if (!_webSocket.Send("{\"action\":\"sub\",\"channel\":\"killstream\"}"))
                        {
                            _webSocket?.Dispose();
                            _webSocket = null;
                            return(null);
                        }

                        await LogHelper.LogInfo("ZKB feed core WebSocket connect successful!", LogCat.ZKill);
                    }
                }

                if (!_webMailsQueue.IsEmpty && _webMailsQueue.TryDequeue(out var km))
                {
                    return(km);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx("GetSocketResponce", ex, LogCat.ZKill);

                _webSocket?.Dispose();
                _webSocket = null;
            }

            return(null);
        }
Beispiel #21
0
        internal static int InvokeHubMethod(PureWebSocket socket, string hubName, string methodName,
                                            params object[] parameters)
        {
            // Transport: ws
            // exmaple which should not be encoded before sending
            // {"H":"chatHub","M":"getOnlineCount","A":[],"I":319104157}
            var msgId = int.Parse(DateTime.Now.ToString("MMddhhmmss"));
            var sb    = new StringBuilder();

            sb.Append($"{{\"H\":\"{hubName}\",\"M\":\"{methodName}\",\"A\":[");
            if (parameters.Length > 0)
            {
                for (var i = 0; i < parameters.Length; i++)
                {
                    var cobj = parameters[i];
                    if (cobj is short || cobj is int || cobj is long || cobj is ushort || cobj is uint || cobj is ulong ||
                        cobj is double || cobj is decimal || cobj is float)
                    {
                        sb.Append(parameters[i]);
                    }
                    else if (cobj is bool)
                    {
                        if ((bool)parameters[i])
                        {
                            sb.Append(1);
                        }
                        else
                        {
                            sb.Append(0);
                        }
                    }
                    else
                    {
                        sb.Append($"\"{parameters[i]}\"");
                    }
                    if (i < parameters.Length - 1)
                    {
                        sb.Append(",");
                    }
                }
            }
            sb.Append($"],\"I\":{msgId}}}");

            if (socket.Send(sb.ToString()))
            {
                return(msgId);
            }
            return(-1);
        }
Beispiel #22
0
        /// <summary>
        /// Generates a listener for socket close events.
        /// </summary>
        /// <param name="connection">A refernce to the connection.</param>
        /// <returns></returns>
        private Closed Socket_OnClosed(IActorRef connection)
        {
            return((WebSocketCloseStatus reason) => {
                Log.Information("Socket closed : {0}.", reason);

                if (_socket.State == WebSocketState.Open ||
                    _socket.State == WebSocketState.CloseReceived ||
                    _socket.State == WebSocketState.CloseSent)
                {
                    _socket.Dispose();
                    _socket = null;
                }

                connection.Tell(new Socket_Disconnected());
            });
        }
Beispiel #23
0
        public void Disconnect(Action callback)
        {
            if (_conn != null)
            {
                // _conn.OnClose(); //TODO how to clear event handler?
                if (_conn.State == WebSocketState.Open)
                {
                    _conn.Disconnect();
                }

                _conn.Dispose();
                _conn = null;
            }

            callback?.Invoke();
        }
Beispiel #24
0
        public LoxoneMiniserverConnection(string address, int port, string username, string password)
        {
            _keepAliveTimer = new Timer(TimeSpan.FromMinutes(4).TotalMilliseconds);
            Address         = address;
            Port            = port;
            Username        = username;
            this.password   = password;

            webApi = new LoxoneWebApi($"http://{address}:{port}", username, password);
            var socketOptions = new PureWebSocketOptions()
            {
                DebugMode = false
            };

            _webSocket = new PureWebSocket($"ws://{address}:{port}/ws/rfc6455", socketOptions);
            _keepAliveTimer.Elapsed += _keepAliveTimer_Elapsed;
        }
Beispiel #25
0
        public static void Main(string[] args)
        {
            _timer = new Timer(OnTick, null, 2000, 1);

RESTART:
            _ws                 = new PureWebSocket("wss://echo.websocket.org", new ReconnectStrategy(10000, 60000));
            _ws.SendDelay       = 100;
            _ws.OnStateChanged += Ws_OnStateChanged;
            _ws.OnMessage      += Ws_OnMessage;
            _ws.OnClosed       += Ws_OnClosed;
            _ws.OnSendFailed   += Ws_OnSendFailed;
            _ws.Connect();

            Console.ReadLine();
            _ws.Dispose(true);
            goto RESTART;
        }
        public PureSocketClusterSocket(string url, PureSocketClusterOptions options)
        {
            _options = options;

            Log("Creating new instance.");

            if (options.Serializer is null)
            {
                options.Serializer = new Utf8JsonSerializer();
            }
            _counter = 0;
            Channels = new List <Channel>();
            _acks    = new Dictionary <long?, object[]>();

            _socket = new PureWebSocket(url, options);

            SetupEvents();
        }
Beispiel #27
0
        private async Task <bool> InitWs()
        {
            _ws = new PureWebSocket("wss://graphigostream.prd.dlive.tv", new PureWebSocketOptions
            {
                DebugMode    = false,
                SubProtocols = new[] { "graphql-ws" }
            });
            _ws.OnOpened += () =>
            {
                _ws.SendAsync("{\"type\":\"connection_init\",\"payload\":{}}\t").Wait();
                _ws.SendAsync("{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{\"streamer\":\"" + _blockchainName + "\"},\"extensions\":{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"916cddf76e8b906a0a39ed0d9ecb2e3b603733cd91ea69235da267084f63f8ad\"}},\"operationName\":\"StreamMessageSubscription\",\"query\":\"subscription StreamMessageSubscription($streamer: String!) {\\n streamMessageReceived(streamer: $streamer) {\\n type\\n ... on ChatGift {\\n id\\n gift\\n amount\\n recentCount\\n expireDuration\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatHost {\\n id\\n viewer\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatSubscription {\\n id\\n month\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatChangeMode {\\n mode\\n __typename\\n }\\n ... on ChatText {\\n id\\n content\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatFollow {\\n id\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatDelete {\\n ids\\n __typename\\n }\\n ... on ChatBan {\\n id\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatModerator {\\n id\\n ...VStreamChatSenderInfoFrag\\n add\\n __typename\\n }\\n ... on ChatEmoteAdd {\\n id\\n ...VStreamChatSenderInfoFrag\\n emote\\n __typename\\n }\\n ... on ChatTimeout {\\n id\\n ...VStreamChatSenderInfoFrag\\n minute\\n __typename\\n }\\n ... on ChatTCValueAdd {\\n id\\n ...VStreamChatSenderInfoFrag\\n amount\\n totalAmount\\n __typename\\n }\\n __typename\\n }\\n}\\n\\nfragment VStreamChatSenderInfoFrag on SenderInfo {\\n subscribing\\n role\\n roomRole\\n sender {\\n id\\n username\\n displayname\\n avatar\\n partnerStatus\\n badges\\n __typename\\n }\\n __typename\\n}\\n\"}}")
                .Wait();
            };
            _ws.OnMessage += OnWebsocketMessage;
            _ws.OnClosed  += reason => { Events.FireOnDisconnect(); };

            return(_ws.ConnectAsync().Result);
        }
        protected override async Task GetExchangeDataAsync(CancellationToken ct)
        {
            var options = new PureWebSocketOptions
            {
                DebugMode = false
            };

            using (var ws = new PureWebSocket(TickerUrl, options))
            {
                var closed = false;

                ws.OnMessage += WsOnMessage;
                ws.OnClosed  += reason =>
                {
                    Logger.Info($"Binance closed: {reason}");
                    closed = true;
                };
                ws.OnError += exception =>
                {
                    Logger.Error(exception);
                    closed = true;
                };

                if (!ws.Connect( ))
                {
                    Logger.Error("Couldn't connect to Binance");
                }

                while (ws.State != WebSocketState.Closed)
                {
                    if (UpTime > LastUpdateDuration &&
                        LastUpdateDuration > TimeSpan.FromHours(1) ||
                        closed)
                    {
                        ws.Disconnect( );
                        break;
                    }

                    await Task.Delay(PollingRate, ct).ConfigureAwait(false);
                }
            }
        }
        /// <summary>
        /// Connects to a Websocket endpoint.
        /// </summary>
        /// <typeparam name="T">Type used to parsed the response message.</typeparam>
        /// <param name="parameters">Paremeters to send to the Websocket.</param>
        /// <param name="messageDelegate">Deletage to callback after receive a message.</param>
        /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param>
        public void ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, bool useCustomParser = false)
        {
            var finalEndpoint = _webSocketEndpoint + parameters;

            var ws = new PureWebSocket(finalEndpoint, new PureWebSocketOptions()
            {
                DebugMode           = false,//true,
                SendDelay           = 10,
                IgnoreCertErrors    = true,
                MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
            });

            ws.OnMessage += (data) =>
            {
                dynamic eventData;

                if (useCustomParser)
                {
                    var customParser = new CustomParser();
                    eventData = customParser.GetParsedDepthMessage(JsonConvert.DeserializeObject <dynamic>(data));
                }
                else
                {
                    eventData = JsonConvert.DeserializeObject <T>(data);
                }

                messageHandler(eventData);
            };

            ws.OnClosed += (reason) =>
            {
                _openSockets.Remove(ws);
            };

            ws.OnError += (error) =>
            {
                _openSockets.Remove(ws);
            };

            ws.Connect();
            _openSockets.Add(ws);
        }
Beispiel #30
0
        public JadiscoApi()
        {
            try
            {
                PureWebSocketOptions socketOptions = new PureWebSocketOptions()
                {
                    DebugMode           = false,
                    MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20)
                };

                webSocket            = new PureWebSocket(WebSocketUrl, socketOptions);
                webSocket.OnMessage += WebSocket_OnMessage;
                webSocket.OnOpened  += WebSocket_OnOpened;
                webSocket.OnClosed  += WebSocket_OnClosed;
                webSocket.OnError   += WebSocket_OnError;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[WS] Error: {ex.Message}");
            }
        }