Beispiel #1
0
 internal void Open(OpenResponse openResponse)
 {
     Id = openResponse.Sid;
     if (_pingToken == null)
     {
         _pingToken = new CancellationTokenSource();
     }
     else
     {
         _pingToken.Cancel();
     }
     Task.Factory.StartNew(async() =>
     {
         await SendNamespaceAsync();
         while (!_pingToken.IsCancellationRequested)
         {
             await Task.Delay(openResponse.PingInterval);
             try
             {
                 PingTime = DateTime.Now;
                 await Socket.SendMessageAsync("2");
                 OnPing?.Invoke(this, new EventArgs());
             }
             catch { }
         }
     }, _pingToken.Token);
 }
Beispiel #2
0
        private void HandleMessage(object sender, TransportMessageEventArgs args)
        {
            var buffer  = args.Buffer;
            var message = _messageSerializer.Deserialize(buffer.Span);

            var remote = new SwimHost(args.RemoteEndpoint);

            switch (message.Type)
            {
            case SwimMessageType.Ping:
                OnPing?.Invoke(this, new TransportPingEventArgs(message as PingMessage, remote));
                break;

            case SwimMessageType.PingReq:
                OnPingReq?.Invoke(this, new TransportPingReqEventArgs(message as PingReqMessage, remote));
                break;

            case SwimMessageType.Ack:
                OnAck?.Invoke(this, new TransportAckEventArgs(message as AckMessage, remote));
                break;

            case SwimMessageType.Sync:
                OnSync?.Invoke(this, new TransportSyncEventArgs(message as SyncMessage, remote));
                break;

            case SwimMessageType.Update:
                OnUpdate?.Invoke(this, new TransportUpdateEventArgs(message as UpdateMessage, remote));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #3
0
        private void OnIncomingMessage(Message message)
        {
            if (State == TcpSocketState.Closed)
            {
                return;
            }
            switch (message.Opcode)
            {
            case 1:
                string str;
                try { str = Encoding.UTF8.GetString(message.Data); }
                catch (ArgumentException) { ForciblyClose(); return; }
                OnString?.Invoke(str);
                break;

            case 2: OnBinary?.Invoke(message.Data); break;

            case 8:
                ushort code   = (ushort)(message.Data.Length == 0 ? 0 : message.Data[0] * 256u + message.Data[1]);
                string reason = message.Data.Length >= 2 ? Encoding.UTF8.GetString(message.Data, 2, message.Data.Length - 2) : null;
                OnClose?.Invoke(code, reason);
                AnswerClose(code, reason);
                break;

            case 9: OnPing?.Invoke(message.Data); AnswerPing(message.Data); break;

            case 10: OnPong?.Invoke(message.Data); break;

            default: ForciblyClose(); break;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Parses and handles raw server messages
        /// </summary>
        /// <param name="message">The raw message from the server</param>
        public void Parse(string message)
        {
            OnAnything.Fire(this, new EventArgs());
            Debug.WriteLine(string.Format("RAW: \"{0}\"", message));

            IrcMessage ircMessage = ParseIrcMessage(message);

            switch (ircMessage.Tokens[0])
            {
            case PING:
                OnPing?.Invoke(ircMessage.Message);
                break;

            case NOTICE:
                OnPrivateNotice.Fire(this, new UserMessageEventArgs(User.Empty, ircMessage.Message));
                break;

            case ERROR:
                Error(ReplyCode.IrcServerError, ircMessage.Message);
                break;

            default:
                if (_replyRegex.IsMatch(message))
                {
                    ParseReply(ircMessage.Tokens);
                }
                else
                {
                    ParseCommand(ircMessage.Tokens);
                }
                break;
            }
        }
Beispiel #5
0
        protected bool HandleMessage(Message message)
        {
            lock (Sync) switch (message.Opcode)
                {
                case 1: OnString?.Invoke(Encoding.UTF8.GetString(message.Payload)); return(true);

                case 2: OnBinary?.Invoke(message.Payload); return(true);

                case 8:
                    if (message.Length < 2)
                    {
                        FinishClose(); return(true);
                    }
                    ushort code   = (ushort)(message.Payload[0] * 256 + message.Payload[1]);
                    string reason = Encoding.UTF8.GetString(PrimitiveBuffer.Slice(message.Payload, 2, message.Length));
                    if (RecvClose && message.Length > 2)
                    {
                        return(false);
                    }
                    if (message.Length > 2)
                    {
                        return(FinishClose(code, reason));
                    }
                    return(FinishClose(code));

                case 9: OnPing?.Invoke(message.Payload); return(true);

                case 10: OnPong?.Invoke(message.Payload); return(true);

                default: return(false);
                }
        }
Beispiel #6
0
        private async void Listen()
        {
            using (Stream ns = Stream) {
                WebSocketReader reader = new WebSocketReader();

                OnHandshake?.Invoke(this, new HandshakeEventArgs(null, null));

                while (Running && !ListenToken.IsCancellationRequested)
                {
                    WebSocketFrame frame = await reader.Read(ns, null);

                    if (frame == null || frame.Opcode == WebSocketOpcode.ConnectionCloseFrame)
                    {
                        Remove(WebSocketDisconnection.Disconnect);
                        break;
                    }

                    switch (frame.Opcode)
                    {
                    case WebSocketOpcode.PingFrame:

                        if (frame.Data.Length <= 125)
                        {
                            await Writer.WritePong(frame);

                            OnPing?.Invoke(this, new PingEventArgs(frame.Data));
                        }

                        break;

                    case WebSocketOpcode.PongFrame:

                        OnPong?.Invoke(this, new PongEventArgs(frame.Data));

                        break;

                    case WebSocketOpcode.BinaryFrame:

                        if (frame.Data.Length == 4 && frame.Data[0] == 22 &&
                            frame.Data[1] == 23 && frame.Data[2] == 24 && frame.Data[3] == 25)
                        {
                            await OnPingReceived();
                        }

                        OnMessage?.Invoke(this, new MessageEventArgs(null, frame));

                        break;

                    case WebSocketOpcode.TextFrame:

                        OnMessage?.Invoke(this, new MessageEventArgs(null, frame));

                        break;
                    }
                }
            }
        }
Beispiel #7
0
        public void Start(string username)
        {
            _stopFlag = false;
            _username = username;

            var hostname = SettingsHelper.GetSetting("ServerHost");

            CreateConnection(hostname);

            _udpClient = new UdpClient();
            _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            _udpClient.ExclusiveAddressUse = false;
            //_udpClient.Connect(SettingsHelper.GetSetting("ServerHost"), 5565);
            //_udpClient.Connect("localhost", 5565);
            //_udpClient.BeginReceive(OnUdpData, _udpClient);

            _injectorThread = new Thread(ProcessPackets)
            {
                Priority = ThreadPriority.AboveNormal, IsBackground = true
            };
            _injectorThread.Start();

            _userDataUpdateThread = new Thread(async() =>
            {
                while (!_stopFlag)
                {
                    try
                    {
                        var stopwatch = new Stopwatch();
                        stopwatch.Start();
                        await _connection.InvokeAsync <string>("Ping");
                        stopwatch.Stop();

                        var clients = await _connection.InvokeAsync <List <ClientConnection> >("GetClients");
                        OnPing?.Invoke(this, new OnPingEventArgs {
                            Ping = stopwatch.ElapsedMilliseconds
                        });
                        OnClientListReceived?.Invoke(this, new OnClientListReceivedEventArgs {
                            Clients = clients
                        });
                        await Task.Delay(5000);
                    }
                    catch (Exception e)
                    {
                        Stop();
                        return;
                    }
                }
            })
            {
                IsBackground = true
            };
        }
        /// <summary>
        /// Listener loop for subscribing google talk events
        /// </summary>
        /// <returns>Returns if the loop is manually break or not</returns>
        private async Task <bool> ListenForIncomingJobsAsync()
        {
            // Async task to listen to google stream for new additions to joblist
            OnXmppDebugLogging?.Invoke(this, "Xmpp Connection - Listener loop started.");

            // Only end when _xmppSslStream is cleaned up (set to null)
            while (_xmppSslStream != null)
            {
                try
                {
                    OnXmppDebugLogging?.Invoke(this, $"Xmpp Connection - Ping at '{DateTime.Now.ToUniversalTime()}'");
                    OnPing?.Invoke(this, new EventArgs());
                    // Asnynchronously wait for new xml incoming from google
                    var xmlDoc = await RecieveXmlAsync().ConfigureAwait(false);

                    if (xmlDoc != null && OnIncomingPrintJobs != null)
                    {
                        // If xml node matches 'push:data', it must contain incoming printjob notification from google
                        var pushData = xmlDoc.GetElementsByTagName("push:data");
                        if (pushData.Count > 0)
                        {
                            // Retrieve printerId & Log
                            var printerIdEncoded = pushData[0].InnerText;
                            var printerId        = Encoding.UTF8.GetString(Convert.FromBase64String(printerIdEncoded));
                            OnXmppDebugLogging?.Invoke(this, $"Xmpp Connection: Recieved job addition event from printer '{printerId}'");

                            OnIncomingPrintJobs?.Invoke(this, new JobRecievedEventArgs {
                                PrinterId = printerId
                            });
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    OnXmppDebugLogging?.Invoke(this, $"Xmpp Connection - An Exception was thrown while listening to google, the listener loop is terminated. Exception: '{ex.Message}'");
                    StopXmpp();
                    return(false);
                }
            }

            OnXmppDebugLogging?.Invoke(this, "Xmpp Connection - Listener loop ended.");
            return(true);
        }
Beispiel #9
0
        private void ProcessRequest(string rawSmeeEvent)
        {
            var eventRegEx    = new Regex("^(.*event: )(.*?)(,.*)$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            var jsonSmeeEvent = eventRegEx.Replace(rawSmeeEvent, "$1\"$2\"$3");
            var smeeEvent     = JsonConvert.DeserializeObject <Models.SmeeEvent>("{" + jsonSmeeEvent + "}");

            switch (smeeEvent.Event)
            {
            case SmeeEventType.Message:
                // Convert to Dto (Could use AutoMapper, but it would add a dependency.
                var dtoSmeeEvent = new Dto.SmeeEvent(smeeEvent);
                OnMessage?.Invoke(this, dtoSmeeEvent);
                break;

            case SmeeEventType.Ping:
                OnPing?.Invoke(this, EventArgs.Empty);
                break;

            case SmeeEventType.Ready:
                OnConnect?.Invoke(this, EventArgs.Empty);
                break;
            }
        }
 public void FireEvent_OnPing(object source, NetworkPingPongArgs args) =>
 OnPing?.Invoke(source, args);
        private async Task ListenClient(WebSocketUser user)
        {
            using (Stream ns = user.Stream) {
                WebSocketReader reader = new WebSocketReader();
                var             res    = await InterpretHeader(user, ns);

                if (!(res.Item1))
                {
                    RemoveClient(user, WebSocketDisconnection.NoHeader);
                    return;
                }

                Logger.DebugWrite("INFO", $"Socket successfully handshaked the update. UID: {user.UID}");
                OnHandshake?.Invoke(this, new HandshakeEventArgs(user, res.Item2));

                while (Running && !user.ListenToken.IsCancellationRequested)
                {
                    WebSocketFrame frame = await reader.Read(ns, user);

                    if (frame == null || frame.Opcode == WebSocketOpcode.ConnectionCloseFrame)
                    {
                        RemoveClient(user, WebSocketDisconnection.Disconnect);
                        break;
                    }

                    switch (frame.Opcode)
                    {
                    case WebSocketOpcode.PingFrame:

                        if (frame.Data.Length <= 125)
                        {
                            await user.Writer.WritePong(frame);

                            OnPing?.Invoke(this, new PingEventArgs(frame.Data));
                        }

                        break;

                    case WebSocketOpcode.PongFrame:

                        OnPong?.Invoke(this, new PongEventArgs(frame.Data));

                        break;

                    case WebSocketOpcode.BinaryFrame:

                        user.Meta.LastTime.Binary = DateTime.UtcNow;

                        if (RttEnabled && frame.Data.Length == 4 && frame.Data[0] == 26 &&
                            frame.Data[1] == 27 && frame.Data[2] == 28 && frame.Data[3] == 29)
                        {
                            OnPongReceived(user);
                        }

                        OnMessage?.Invoke(this, new MessageEventArgs(user, frame));

                        break;

                    case WebSocketOpcode.TextFrame:

                        user.Meta.LastTime.Text = DateTime.UtcNow;

                        OnMessage?.Invoke(this, new MessageEventArgs(user, frame));

                        break;
                    }
                }
            }
        }
Beispiel #12
0
 public void Ping()
 {
     OnPing?.Invoke(this, EventArgs.Empty);
 }
Beispiel #13
0
 public override Task <RpcCommunicationDiscord.PingResponse> Ping(RpcCommunicationDiscord.PingRequest request, ServerCallContext context)
 {
     OnPing?.Invoke(this, new PingRequest());
     return(Task.FromResult(new RpcCommunicationDiscord.PingResponse()));
 }
Beispiel #14
0
        private async Task <Message> WireDecodeMessage(UInt32 magic)
        {
            var command         = DataDecoder.DecodeFixedString(await ReceiveExactly(12));
            var payloadSize     = DataDecoder.DecodeUInt32(await ReceiveExactly(4));
            var payloadChecksum = DataDecoder.DecodeUInt32(await ReceiveExactly(4));
            var payload         = await ReceiveExactly(payloadSize.ToIntChecked());

            if (!Messaging.VerifyPayloadChecksum(payloadChecksum, payload))
            {
                throw new Exception($"Checksum failed for {command}");
            }

            var message = new Message
                          (
                Magic: magic,
                Command: command,
                PayloadSize: payloadSize,
                PayloadChecksum: payloadChecksum,
                Payload: payload.ToImmutableArray()
                          );

            switch (message.Command)
            {
            case "addr":
            {
                var addressPayload = NetworkEncoder.DecodeAddressPayload(payload);

                OnReceivedAddresses?.Invoke(owner, addressPayload.NetworkAddresses);
            }
            break;

            case "alert":
            {
                var alertPayload = NetworkEncoder.DecodeAlertPayload(payload);
            }
            break;

            case "block":
            {
                var block = DataDecoder.DecodeBlock(null, payload);

                OnBlock?.Invoke(owner, block);
            }
            break;

            case "getblocks":
            {
                var getBlocksPayload = NetworkEncoder.DecodeGetBlocksPayload(payload);

                OnGetBlocks?.Invoke(owner, getBlocksPayload);
            }
            break;

            case "getheaders":
            {
                var getHeadersPayload = NetworkEncoder.DecodeGetBlocksPayload(payload);

                OnGetHeaders?.Invoke(owner, getHeadersPayload);
            }
            break;

            case "getdata":
            {
                var invPayload = NetworkEncoder.DecodeInventoryPayload(payload);

                OnGetData?.Invoke(owner, invPayload);
            }
            break;

            case "headers":
            {
                var blockHeaders = ImmutableList.CreateBuilder <BlockHeader>();

                var offset      = 0;
                var headerCount = payload.ReadVarInt(ref offset).ToIntChecked();

                for (var i = 0; i < headerCount; i++)
                {
                    var blockHeader = DataDecoder.DecodeBlockHeader(null, payload, ref offset);
                    // ignore tx count var int
                    payload.ReadVarInt(ref offset);

                    blockHeaders.Add(blockHeader);
                }

                OnBlockHeaders?.Invoke(owner, blockHeaders.ToImmutable());
            }
            break;

            case "inv":
            {
                var invPayload = NetworkEncoder.DecodeInventoryPayload(payload);

                OnInventoryVectors?.Invoke(owner, invPayload.InventoryVectors);
            }
            break;

            case "notfound":
            {
                var invPayload = NetworkEncoder.DecodeInventoryPayload(payload);

                OnNotFound?.Invoke(owner, invPayload.InventoryVectors);
            }
            break;

            case "ping":
            {
                OnPing?.Invoke(owner, payload.ToImmutableArray());
            }
            break;

            case "tx":
            {
                var tx = DataDecoder.DecodeEncodedTx(null, payload);

                OnTransaction?.Invoke(owner, tx);
            }
            break;

            case "version":
            {
                var versionPayload = NetworkEncoder.DecodeVersionPayload(payload, payload.Length);

                OnVersion?.Invoke(owner, versionPayload);
            }
            break;

            case "verack":
            {
                OnVersionAcknowledged?.Invoke(owner);
            }
            break;

            default:
            {
                logger.Warn($"Unhandled incoming message: {message.Command}");
            }
            break;
            }

            //TODO
            //if (payloadStream.Position != payloadStream.Length)
            //{
            //    var exMessage = $"Wrong number of bytes read for {message.Command}, parser error: read {payloadStream.Position} bytes from a {payloadStream.Length} byte payload";
            //    Debug.WriteLine(exMessage);
            //    throw new Exception(exMessage);
            //}

            return(message);
        }
Beispiel #15
0
        private void onMessage(object sender, MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }
            JObject json = JObject.Parse(e.Data);

            if (json.SelectToken("type") != null)
            {
                switch (json.SelectToken("type").ToString())
                {
                case "command":
                    OnPing?.Invoke(client, new Events.Client.OnPingArgs {
                        UUID = json.SelectToken("extra").SelectToken("uuid").ToString()
                    });
                    break;

                case "follow":
                    OnFollow?.Invoke(client, new Events.Client.OnFollowArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.Follow.Extra(json.SelectToken("extra")),
                        Viewer      = new Models.Client.Viewer(json.SelectToken("viewer"))
                    });
                    break;

                case "subscribe":
                    OnSubscriber?.Invoke(client, new Events.Client.OnSubscriberArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.Sub.Extra(json.SelectToken("extra")),
                        Viewer      = new Models.Client.Viewer(json.SelectToken("viewer"))
                    });
                    break;

                case "points_given":
                    OnBits?.Invoke(client, new Events.Client.OnBitsArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.Bits.Extra(json.SelectToken("extra")),
                        Viewer      = new Models.Client.Viewer(json.SelectToken("viewer"))
                    });
                    break;

                case "session_change":
                    OnSessionChanged?.Invoke(client, new Events.Client.OnSessionChangeArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.SessionChange.Extra(json.SelectToken("extra"))
                    });
                    break;

                case "hosted":
                    OnHosted?.Invoke(client, new Events.Client.OnHostedArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.Hosted.Extra(json.SelectToken("extra")),
                        Viewer      = new Models.Client.Viewer(json.SelectToken("viewer"))
                    });
                    break;

                case "donate":
                    OnDonation?.Invoke(client, new Events.Client.OnDonationArgs
                    {
                        Channel     = json.SelectToken("channel").ToString(),
                        Date        = Internal.Common.DateTimeStringToObject(json.SelectToken("date").ToString()),
                        Message     = json.SelectToken("message")?.ToString(),
                        UserMessage = json.SelectToken("user_message")?.ToString(),
                        Extra       = new Models.Client.Donation.Extra(json.SelectToken("extra")),
                        Viewer      = new Models.Client.Viewer(json.SelectToken("viewer"))
                    });
                    break;
                }
            }
        }
Beispiel #16
0
        private async Task ReadStream()
        {
            while (!Closing)
            {
                try
                {
                    //try to read a header
                    var hdata = new byte[24];
                    await Stream.ReadAsyncExact(hdata, 0, hdata.Length);

                    var h = new MessageHeader();
                    h.ReadFromPayload(hdata, 0);
                    if (h != null)
                    {
                        //read the payload
                        var pl = new byte[h.PayloadSize];
                        await Stream.ReadAsyncExact(pl, 0, pl.Length);

                        bool checksumOk = false;

                        //verify hash
                        using (var sha = SHA256.Create())
                        {
                            var h1 = sha.ComputeHash(pl);
                            var h2 = sha.ComputeHash(h1);

                            checksumOk = h2[0] == h.Checksum[0] && h2[1] == h.Checksum[1] && h2[2] == h.Checksum[2] && h2[3] == h.Checksum[3];
                        }

                        if (checksumOk)
                        {
                            switch (h.Command)
                            {
                            case "addr\0\0\0\0\0\0\0\0":
                            {
                                if (OnAddr != null)
                                {
                                    var a = new Addr();
                                    a.ReadFromPayload(pl, 0);

                                    await OnAddr?.Invoke(this, a);
                                }
                                break;
                            }

                            case "alert\0\0\0\0\0\0\0":
                            {
                                if (OnAlert != null)
                                {
                                    var a = new Alert();
                                    a.ReadFromPayload(pl, 0);

                                    await OnAlert?.Invoke(this, a);
                                }
                                break;
                            }

                            case "feefilter\0\0\0":
                            {
                                if (OnFeeFilter != null)
                                {
                                    var f = new FeeFilter();
                                    f.ReadFromPayload(pl, 0);

                                    await OnFeeFilter?.Invoke(this, f);
                                }
                                break;
                            }

                            case "filteradd\0\0\0":
                            {
                                if (OnFilterAdd != null)
                                {
                                    var f = new FilterAdd();
                                    f.ReadFromPayload(pl, 0);

                                    await OnFilterAdd?.Invoke(this, f);
                                }
                                break;
                            }

                            case "filterclear\0":
                            {
                                if (OnFilterClear != null)
                                {
                                    var f = new FilterClear();
                                    f.ReadFromPayload(pl, 0);

                                    await OnFilterClear?.Invoke(this, f);
                                }
                                break;
                            }

                            case "filterload\0\0":
                            {
                                if (OnFilterLoad != null)
                                {
                                    var f = new FilterLoad();
                                    f.ReadFromPayload(pl, 0);

                                    await OnFilterLoad?.Invoke(this, f);
                                }
                                break;
                            }

                            case "getaddr\0\0\0\0\0":
                            {
                                if (OnGetAddr != null)
                                {
                                    var ga = new GetAddr();
                                    ga.ReadFromPayload(pl, 0);

                                    await OnGetAddr?.Invoke(this, ga);
                                }
                                break;
                            }

                            case "getblocks\0\0\0":
                            {
                                if (OnGetBlocks != null)
                                {
                                    var gb = new GetBlocks();
                                    gb.ReadFromPayload(pl, 0);

                                    await OnGetBlocks?.Invoke(this, gb);
                                }
                                break;
                            }

                            case "getdata\0\0\0\0\0":
                            {
                                if (OnGetData != null)
                                {
                                    var gd = new GetData();
                                    gd.ReadFromPayload(pl, 0);

                                    await OnGetData?.Invoke(this, gd);
                                }
                                break;
                            }

                            case "getheaders\0\0":
                            {
                                if (OnGetHeaders != null)
                                {
                                    var gh = new GetHeaders();
                                    gh.ReadFromPayload(pl, 0);

                                    await OnGetHeaders?.Invoke(this, gh);
                                }
                                break;
                            }

                            case "headers\0\0\0\0\0":
                            {
                                if (OnHeaders != null)
                                {
                                    var hd = new Headers();
                                    hd.ReadFromPayload(pl, 0);

                                    await OnHeaders?.Invoke(this, hd);
                                }
                                break;
                            }

                            case "inv\0\0\0\0\0\0\0\0\0":
                            {
                                if (OnInv != null)
                                {
                                    var iv = new Inv();
                                    iv.ReadFromPayload(pl, 0);

                                    await OnInv?.Invoke(this, iv);
                                }
                                break;
                            }

                            case "mempool\0\0\0\0\0":
                            {
                                if (OnMemPool != null)
                                {
                                    var mp = new MemPool();
                                    mp.ReadFromPayload(pl, 0);

                                    await OnMemPool?.Invoke(this, mp);
                                }
                                break;
                            }

                            case "notfound\0\0\0\0":
                            {
                                if (OnNotFound != null)
                                {
                                    var nf = new NotFound();
                                    nf.ReadFromPayload(pl, 0);

                                    await OnNotFound?.Invoke(this, nf);
                                }
                                break;
                            }

                            case "ping\0\0\0\0\0\0\0\0":
                            {
                                if (OnPing != null)
                                {
                                    var ping = new Ping();
                                    ping.ReadFromPayload(pl, 0);

                                    await OnPing?.Invoke(this, ping);
                                }
                                break;
                            }

                            case "pong\0\0\0\0\0\0\0\0":
                            {
                                if (OnPong != null)
                                {
                                    var pong = new Pong();
                                    pong.ReadFromPayload(pl, 0);

                                    await OnPong?.Invoke(this, pong);
                                }
                                break;
                            }

                            case "reject\0\0\0\0\0\0":
                            {
                                if (OnReject != null)
                                {
                                    var re = new Reject();
                                    re.ReadFromPayload(pl, 0);

                                    await OnReject?.Invoke(this, re);
                                }
                                break;
                            }

                            case "sendheaders\0":
                            {
                                if (OnSendHeaders != null)
                                {
                                    var sh = new SendHeaders();
                                    sh.ReadFromPayload(pl, 0);

                                    await OnSendHeaders?.Invoke(this, sh);
                                }
                                break;
                            }

                            case "verack\0\0\0\0\0\0":
                            {
                                if (OnVerAck != null)
                                {
                                    var va = new VerAck();
                                    va.ReadFromPayload(pl, 0);

                                    await OnVerAck.Invoke(this, va);
                                }
                                break;
                            }

                            case "version\0\0\0\0\0":
                            {
                                if (OnVersion != null)
                                {
                                    var v = new bitcoin_lib.P2P.Version("");
                                    v.ReadFromPayload(pl, 0);

                                    await OnVersion?.Invoke(this, v);
                                }
                                break;
                            }

                            default:
                            {
                                //Console.WriteLine($"Got cmd: {h.Command}");
                                break;
                            }
                            }
                        }
                        else
                        {
                            Closing = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Closing = true;
                }
            }
        }
Beispiel #17
0
 public void InvokePingAsync()
 {
     OnPing?.Invoke();
 }
Beispiel #18
0
 public Task PingAsync(string message)
 {
     OnPing?.Invoke(message);
     OnPingNoArg?.Invoke();
     return(Task.CompletedTask);
 }
Beispiel #19
0
        private async void ReceiverLoop(object obj)
        {
            WebSocketReceiveResult r;
            var buffer        = new byte[ReceiveChunkSize];
            var bufferSegment = new ArraySegment <byte>(buffer);



            pingRequestDeadline = Environment.TickCount + (int)PingInterval.TotalMilliseconds;
            pongTimeoutDeadline = Environment.TickCount + (int)PingTimeout.TotalMilliseconds;
            Task <WebSocketReceiveResult> tReceive = null;
            Task tPing = null;

            while (_socket.State == WebSocketState.Open)
            {
                try
                {
                    if (tReceive == null)
                    {
                        tReceive = _socket.ReceiveAsync(bufferSegment, CancellationToken.None);
                    }
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                if (tPing == null)
                {
                    tPing = Task.Delay(Math.Max(0, Math.Min(pingRequestDeadline - Environment.TickCount, pongTimeoutDeadline - Environment.TickCount)));
                }

                var t = await Task.WhenAny(tReceive, tPing);

                if (t == tReceive)
                {
                    try
                    {
                        r        = await tReceive;
                        tReceive = null;
                    }
                    catch (WebSocketException)
                    {
                        // Disconnection?
                        break;
                    }

                    switch (r.MessageType)
                    {
                    case WebSocketMessageType.Text:
                        if (r.Count > 0)
                        {
                            // Defalut engine.io protocol
                            switch (buffer[0])
                            {
                            case (byte)'3':         // Server Pong
                                pongTimeoutDeadline = Environment.TickCount + (int)PingTimeout.TotalMilliseconds;
                                PingEventArgs pingArgs = new PingEventArgs(pingRequestAt, Environment.TickCount);
                                OnPing?.Invoke(pingArgs);
                                break;

                            case (byte)'4':         // Message
                                if (r.Count > 1)
                                {
                                    // Defalut socket.io protocol
                                    switch (buffer[1])
                                    {               // Ignore All of them. it's just for understanding !
                                    case (byte)'0': // Connect
                                    case (byte)'1': // Disconnect
                                        // Ignored
                                        break;

                                    case (byte)'2':             // Event
                                    case (byte)'3':             // Ack
                                    case (byte)'4':             // Error
                                    case (byte)'5':             // Binary_Event
                                    case (byte)'6':             // Binary_Ack
                                        // Ignored
                                        break;
                                    }
                                }

                                // Listen to message
                                var    builder = new StringBuilder();
                                string str     = Encoding.UTF8.GetString(buffer, 0, r.Count);
                                builder.Append(str);

                                while (!r.EndOfMessage)
                                {
                                    r = await _socket.ReceiveAsync(new ArraySegment <byte>(buffer), _tokenSource.Token);

                                    str = Encoding.UTF8.GetString(buffer, 0, r.Count);
                                    builder.Append(str);
                                }

                                var parser = new ResponseTextParser(_namespace, this)
                                {
                                    Text = builder.ToString()
                                };
                                await parser.ParseAsync();


                                break;
                            }
                        }

                        break;

                    case WebSocketMessageType.Binary:
                    case WebSocketMessageType.Close:
                    default:
                        // Nothing to handle
                        break;
                    }
                }
                else
                {
                    if (Environment.TickCount - pingRequestDeadline >= 0)
                    {
                        if (Interlocked.CompareExchange(ref pingRequest, 1, 0) == 0)
                        {
                            pingRequest = 1;
                            WakeSenderLoop();
                            pingRequestDeadline = Environment.TickCount + (int)PingInterval.TotalMilliseconds;
                            pongTimeoutDeadline = Environment.TickCount + (int)PingTimeout.TotalMilliseconds;
                        }
                    }
                    if (Environment.TickCount - pongTimeoutDeadline >= 0)
                    {
                        // Ping timeout
                        try
                        {
                            await _socket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "Ping timeout", CancellationToken.None);
                        }
                        catch (WebSocketException) { }
                        catch (ObjectDisposedException) { }
                        break;
                    }
                }
            }

            serverCloseReason = ServerCloseReason.SocketAborted;
            await CloseAsync();
        }
Beispiel #20
0
 public void DoPing()
 {
     Thread.Sleep(1000);
     Console.WriteLine("Ping");
     OnPing?.Invoke();
 }