protected async Task rejoinChannels() { foreach (var entry in this.channels) { var message = new IntrinioMessage() { Topic = this.parseTopic(entry.Key), Event = "phx_join" }; await sendMessage(message, CancellationToken.None); this.debug("Rejoined channel: ", entry.Key); } }
protected async Task sendMessage <T>(IntrinioMessage <T> message, CancellationToken _cancellationToken) { var messageString = Newtonsoft.Json.JsonConvert.SerializeObject(message); var messageBuffer = Encoding.UTF8.GetBytes(messageString); var messagesCount = (int)Math.Ceiling((double)messageBuffer.Length / bufferSize); for (var i = 0; i < messagesCount; i++) { var offset = (bufferSize * i); var count = bufferSize; var lastMessage = ((i + 1) == messagesCount); if ((count * (i + 1)) > messageBuffer.Length) { count = messageBuffer.Length - offset; } await websocket.SendAsync(new ArraySegment <byte>(messageBuffer, offset, count), WebSocketMessageType.Text, lastMessage, _cancellationToken); } }
protected async void recieveMessages(CancellationToken cancelationToken) { try { var buffer = new byte[bufferSize]; while (this.websocket.State == WebSocketState.Open && !cancelationToken.IsCancellationRequested) { WebSocketReceiveResult result; var stringResult = new StringBuilder(); do { result = await websocket.ReceiveAsync(new ArraySegment <byte>(buffer), cancelationToken); if (result.MessageType == WebSocketMessageType.Close) { await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancelationToken); this.connected = false; } else { var str = Encoding.UTF8.GetString(buffer, 0, result.Count); stringResult.Append(str); } } while (!result.EndOfMessage && !cancelationToken.IsCancellationRequested); if (!cancelationToken.IsCancellationRequested) { IntrinioMessage <Quote> message = Newtonsoft.Json.JsonConvert.DeserializeObject <IntrinioMessage <Quote> >(stringResult.ToString()); if (message.Event == IntrinioMessage <Quote> .MessageType.QUOTE) { var quote = message.Payload; if (OnQuote != null) { OnQuote.DynamicInvoke(this, quote); } debug("Quote: ", quote); } else { debug("Non-quote message: ", stringResult.ToString()); } } } } catch (WebSocketException e) { if (websocket.CloseStatus.HasValue && websocket.CloseStatus.Value != WebSocketCloseStatus.NormalClosure) { socketcancelation.Cancel(); } else { trySelfHeal(); debug("Websocket closed!"); Console.WriteLine("IntrinioRealtime | Websocket error: " + e); } } catch (Exception e) { trySelfHeal(); debug("Websocket closed!"); Console.WriteLine("IntrinioRealtime | Websocket error: " + e); } }