Example #1
0
        protected override void OnReceived(byte[] data)
        {
            if (!_isHandSharked)
            {
                _cache.AddRange(data);

                try
                {
                    var    handShakeText = Encoding.UTF8.GetString(_cache.ToArray());
                    string key           = string.Empty;
                    Regex  reg           = new Regex(@"Sec\-WebSocket\-Accept:(.*?)\r\n");
                    Match  m             = reg.Match(handShakeText);
                    if (string.IsNullOrEmpty(m.Value))
                    {
                        throw new Exception("回复中不存在 Sec-WebSocket-Accept");
                    }
                    key            = Regex.Replace(m.Value, @"Sec\-WebSocket\-Accept:(.*?)\r\n", "$1").Trim();
                    _isHandSharked = true;
                }
                catch (Exception ex)
                {
                    OnError.Invoke(UserToken.ID, ex);
                }
            }
            else
            {
                var coder = (WSCoder)UserToken.Unpacker;

                coder.Unpack(data, (d) =>
                {
                    var wsProtocal = (WSProtocal)d;
                    switch (wsProtocal.Type)
                    {
                    case (byte)WSProtocalType.Close:
                        base.Disconnect();
                        break;

                    case (byte)WSProtocalType.Pong:
                        var date = DateTime.Parse(Encoding.UTF8.GetString(wsProtocal.Content));
                        OnPong?.Invoke(date);
                        break;

                    case (byte)WSProtocalType.Binary:
                    case (byte)WSProtocalType.Text:
                    case (byte)WSProtocalType.Cont:
                        OnMessage?.Invoke((WSProtocal)d);
                        break;

                    case (byte)WSProtocalType.Ping:
                        ReplyPong();
                        break;

                    default:
                        var error = string.Format("收到未定义的Opcode={0}", d.Type);
                        break;
                    }
                }, null, null);
            }
        }
Example #2
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;
                    }
                }
            }
        }
Example #3
0
        protected void OnReceived(byte[] data)
        {
            if (!_isHandSharked)
            {
                _isHandSharked = WSUserToken.AnalysisHandSharkReply(data);
            }
            else
            {
                var coder = (WSCoder)_wsContext.Unpacker;

                coder.Unpack(data, (d) =>
                {
                    var wsProtocal = (WSProtocal)d;
                    switch (wsProtocal.Type)
                    {
                    case (byte)WSProtocalType.Close:
                        _client.Disconnect();
                        break;

                    case (byte)WSProtocalType.Pong:
                        OnPong?.Invoke(Encoding.UTF8.GetString(wsProtocal.Content));
                        break;

                    case (byte)WSProtocalType.Binary:
                    case (byte)WSProtocalType.Text:
                    case (byte)WSProtocalType.Cont:
                        OnMessage?.Invoke((WSProtocal)d);
                        break;

                    case (byte)WSProtocalType.Ping:
                        ReplyPong();
                        break;

                    default:
                        var error = string.Format("收到未定义的Opcode={0}", d.Type);
                        break;
                    }
                }, null, null);
            }
        }
Example #4
0
 internal void InvokePong(TimeSpan ms)
 {
     OnPong?.Invoke(this, ms);
 }
Example #5
0
 public void RaiseOnPong()
 {
     OnPong?.Invoke(DateTime.MinValue);
 }
 public void FireEvent_OnPong(object source, NetworkPingPongArgs args) =>
 OnPong?.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;
                    }
                }
            }
        }
Example #8
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;
                }
            }
        }
Example #9
0
 public async Task InvokePongAsync()
 {
     OnPong?.Invoke("pong received");
 }
Example #10
0
 public void DoPong()
 {
     Thread.Sleep(1000);
     Console.WriteLine("Pong");
     OnPong?.Invoke();
 }