コード例 #1
0
        public void GlobalSetup()
        {
            switch (HubProtocol)
            {
            case Protocol.MsgPack:
                _hubProtocolReaderWriter = new HubProtocolReaderWriter(new MessagePackHubProtocol(), new PassThroughEncoder());
                break;

            case Protocol.Json:
                _hubProtocolReaderWriter = new HubProtocolReaderWriter(new JsonHubProtocol(), new PassThroughEncoder());
                break;
            }

            switch (Input)
            {
            case Message.NoArguments:
                _hubMessage = new InvocationMessage("123", true, "Target", null);
                break;

            case Message.FewArguments:
                _hubMessage = new InvocationMessage("123", true, "Target", null, 1, "Foo", 2.0f);
                break;

            case Message.ManyArguments:
                _hubMessage = new InvocationMessage("123", true, "Target", null, 1, "string", 2.0f, true, (byte)9, new byte[] { 5, 4, 3, 2, 1 }, 'c', 123456789101112L);
                break;

            case Message.LargeArguments:
                _hubMessage = new InvocationMessage("123", true, "Target", null, new string('F', 10240), new byte[10240]);
                break;
            }

            _binaryInput = GetBytes(_hubMessage);
            _binder      = new TestBinder(_hubMessage);
        }
コード例 #2
0
        private async Task StartAsyncCore()
        {
            var transferModeFeature = _connection.Features.Get <ITransferModeFeature>();

            if (transferModeFeature == null)
            {
                transferModeFeature = new TransferModeFeature();
                _connection.Features.Set(transferModeFeature);
            }

            var requestedTransferMode =
                _protocol.Type == ProtocolType.Binary
                    ? TransferMode.Binary
                    : TransferMode.Text;

            transferModeFeature.TransferMode = requestedTransferMode;
            await _connection.StartAsync();

            var actualTransferMode = transferModeFeature.TransferMode;

            _protocolReaderWriter = new HubProtocolReaderWriter(_protocol, GetDataEncoder(requestedTransferMode, actualTransferMode));

            _logger.HubProtocol(_protocol.Name);

            using (var memoryStream = new MemoryStream())
            {
                NegotiationProtocol.WriteMessage(new NegotiationMessage(_protocol.Name), memoryStream);
                await _connection.SendAsync(memoryStream.ToArray(), _connectionActive.Token);
            }
        }
コード例 #3
0
ファイル: TestClient.cs プロジェクト: pardahlman/SignalR
        public TestClient(bool synchronousCallbacks = false, IHubProtocol protocol = null, IDataEncoder dataEncoder = null, IInvocationBinder invocationBinder = null, bool addClaimId = false)
        {
            var options = new PipeOptions(readerScheduler: synchronousCallbacks ? PipeScheduler.Inline : null);
            var pair    = DuplexPipe.CreateConnectionPair(options, options);

            Connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application);

            var claimValue = Interlocked.Increment(ref _id).ToString();
            var claims     = new List <Claim> {
                new Claim(ClaimTypes.Name, claimValue)
            };

            if (addClaimId)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, claimValue));
            }

            Connection.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            Connection.Metadata["ConnectedTask"] = new TaskCompletionSource <bool>();

            protocol              = protocol ?? new JsonHubProtocol();
            dataEncoder           = dataEncoder ?? new PassThroughEncoder();
            _protocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder);
            _invocationBinder     = invocationBinder ?? new DefaultInvocationBinder();

            _cts = new CancellationTokenSource();

            using (var memoryStream = new MemoryStream())
            {
                NegotiationProtocol.WriteMessage(new NegotiationMessage(protocol.Name), memoryStream);
                Connection.Application.Output.WriteAsync(memoryStream.ToArray());
            }
        }
コード例 #4
0
        public TestClient(bool synchronousCallbacks = false)
        {
            var options = new ChannelOptimizations {
                AllowSynchronousContinuations = synchronousCallbacks
            };
            var transportToApplication = Channel.CreateUnbounded <byte[]>(options);
            var applicationToTransport = Channel.CreateUnbounded <byte[]>(options);

            Application = ChannelConnection.Create <byte[]>(input: applicationToTransport, output: transportToApplication);
            _transport  = ChannelConnection.Create <byte[]>(input: transportToApplication, output: applicationToTransport);

            Connection      = new DefaultConnectionContext(Guid.NewGuid().ToString(), _transport, Application);
            Connection.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, Interlocked.Increment(ref _id).ToString()) }));
            Connection.Metadata["ConnectedTask"] = new TaskCompletionSource <bool>();

            var protocol = new JsonHubProtocol(new JsonSerializer());

            _protocolReaderWriter = new HubProtocolReaderWriter(protocol, new PassThroughEncoder());

            _cts = new CancellationTokenSource();

            using (var memoryStream = new MemoryStream())
            {
                NegotiationProtocol.WriteMessage(new NegotiationMessage(protocol.Name), memoryStream);
                Application.Out.TryWrite(memoryStream.ToArray());
            }
        }
コード例 #5
0
        public static Mock <HubConnectionContext> CreateMock(DefaultConnectionContext connection)
        {
            var mock = new Mock <HubConnectionContext>(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance)
            {
                CallBase = true
            };
            var readerWriter = new HubProtocolReaderWriter(new JsonHubProtocol(), new PassThroughEncoder());

            mock.SetupGet(m => m.ProtocolReaderWriter).Returns(readerWriter);
            return(mock);
        }
コード例 #6
0
        internal async Task <bool> NegotiateAsync(TimeSpan timeout, IHubProtocolResolver protocolResolver, IUserIdProvider userIdProvider)
        {
            try
            {
                using (var cts = new CancellationTokenSource())
                {
                    cts.CancelAfter(timeout);
                    while (await _connectionContext.Transport.Reader.WaitToReadAsync(cts.Token))
                    {
                        while (_connectionContext.Transport.Reader.TryRead(out var buffer))
                        {
                            if (NegotiationProtocol.TryParseMessage(buffer, out var negotiationMessage))
                            {
                                var protocol = protocolResolver.GetProtocol(negotiationMessage.Protocol, this);

                                var transportCapabilities = Features.Get <IConnectionTransportFeature>()?.TransportCapabilities
                                                            ?? throw new InvalidOperationException("Unable to read transport capabilities.");

                                var dataEncoder = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) == 0)
                                    ? (IDataEncoder)Base64Encoder
                                    : PassThroughEncoder;

                                var transferModeFeature = Features.Get <ITransferModeFeature>() ??
                                                          throw new InvalidOperationException("Unable to read transfer mode.");

                                transferModeFeature.TransferMode =
                                    (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) != 0)
                                        ? TransferMode.Binary
                                        : TransferMode.Text;

                                ProtocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder);

                                _logger.UsingHubProtocol(protocol.Name);

                                UserIdentifier = userIdProvider.GetUserId(this);

                                return(true);
                            }
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                _logger.NegotiateCanceled();
            }

            return(false);
        }
コード例 #7
0
        private async Task StartAsyncCore()
        {
            var transferModeFeature = GetOrAddTransferModeFeature();
            var requestedMode       = transferModeFeature.TransferMode;

            await _connection.StartAsync();

            var actualMode = transferModeFeature.TransferMode;

            _protocolReaderWriter = GetProtocolReaderWriter(requestedMode, actualMode);

            await NegotiateProtocol();

            _needKeepAlive = _connection.Features.Get <IConnectionInherentKeepAliveFeature>() == null;
            ResetTimeoutTimer();
        }
コード例 #8
0
ファイル: HubMessage.cs プロジェクト: pardahlman/SignalR
        public byte[] WriteMessage(HubProtocolReaderWriter protocolReaderWriter)
        {
            for (var i = 0; i < _serializedMessages.Count; i++)
            {
                if (_serializedMessages[i].ProtocolReaderWriter.Equals(protocolReaderWriter))
                {
                    return(_serializedMessages[i].Message);
                }
            }

            var bytes = protocolReaderWriter.WriteMessage(this);

            // We don't want to balloon memory if someone writes a poor IHubProtocolResolver
            // So we cap how many caches we store and worst case just serialize the message for every connection
            if (_serializedMessages.Count < 10)
            {
                _serializedMessages.Add(new SerializedMessage(protocolReaderWriter, bytes));
            }

            return(bytes);
        }
コード例 #9
0
ファイル: TestClient.cs プロジェクト: xscript/SignalR
        public TestClient(bool synchronousCallbacks = false, IHubProtocol protocol = null, IInvocationBinder invocationBinder = null, bool addClaimId = false)
        {
            var options = new UnboundedChannelOptions {
                AllowSynchronousContinuations = synchronousCallbacks
            };
            var transportToApplication = Channel.CreateUnbounded <byte[]>(options);
            var applicationToTransport = Channel.CreateUnbounded <byte[]>(options);

            Application = ChannelConnection.Create <byte[]>(input: applicationToTransport, output: transportToApplication);
            _transport  = ChannelConnection.Create <byte[]>(input: transportToApplication, output: applicationToTransport);

            Connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), _transport, Application);

            var claimValue = Interlocked.Increment(ref _id).ToString();
            var claims     = new List <Claim> {
                new Claim(ClaimTypes.Name, claimValue)
            };

            if (addClaimId)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, claimValue));
            }

            Connection.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            Connection.Metadata["ConnectedTask"] = new TaskCompletionSource <bool>();

            protocol = protocol ?? new JsonHubProtocol();
            _protocolReaderWriter = new HubProtocolReaderWriter(protocol, new PassThroughEncoder());
            _invocationBinder     = invocationBinder ?? new DefaultInvocationBinder();

            _cts = new CancellationTokenSource();

            using (var memoryStream = new MemoryStream())
            {
                NegotiationProtocol.WriteMessage(new NegotiationMessage(protocol.Name), memoryStream);
                Application.Writer.TryWrite(memoryStream.ToArray());
            }
        }
コード例 #10
0
ファイル: HubConnection.cs プロジェクト: pardahlman/SignalR
        private async Task StartAsyncCore()
        {
            var transferModeFeature = _connection.Features.Get <ITransferModeFeature>();

            if (transferModeFeature == null)
            {
                transferModeFeature = new TransferModeFeature();
                _connection.Features.Set(transferModeFeature);
            }

            var requestedTransferMode =
                _protocol.Type == ProtocolType.Binary
                    ? TransferMode.Binary
                    : TransferMode.Text;

            transferModeFeature.TransferMode = requestedTransferMode;
            await _connection.StartAsync();

            _needKeepAlive = _connection.Features.Get <IConnectionInherentKeepAliveFeature>() == null;

            var actualTransferMode = transferModeFeature.TransferMode;

            _protocolReaderWriter = new HubProtocolReaderWriter(_protocol, GetDataEncoder(requestedTransferMode, actualTransferMode));

            Log.HubProtocol(_logger, _protocol.Name);

            _connectionActive = new CancellationTokenSource();
            using (var memoryStream = new MemoryStream())
            {
                Log.SendingHubNegotiate(_logger);
                NegotiationProtocol.WriteMessage(new NegotiationMessage(_protocol.Name), memoryStream);
                await _connection.SendAsync(memoryStream.ToArray(), _connectionActive.Token);
            }

            ResetTimeoutTimer();
        }
コード例 #11
0
        internal async Task <bool> NegotiateAsync(TimeSpan timeout, IList <string> supportedProtocols, IHubProtocolResolver protocolResolver, IUserIdProvider userIdProvider)
        {
            try
            {
                using (var cts = new CancellationTokenSource())
                {
                    cts.CancelAfter(timeout);

                    while (true)
                    {
                        var result = await _connectionContext.Transport.Input.ReadAsync(cts.Token);

                        var buffer   = result.Buffer;
                        var consumed = buffer.End;
                        var examined = buffer.End;

                        try
                        {
                            if (!buffer.IsEmpty)
                            {
                                if (NegotiationProtocol.TryParseMessage(buffer, out var negotiationMessage, out consumed, out examined))
                                {
                                    var protocol = protocolResolver.GetProtocol(negotiationMessage.Protocol, supportedProtocols, this);

                                    var transportCapabilities = Features.Get <IConnectionTransportFeature>()?.TransportCapabilities
                                                                ?? throw new InvalidOperationException("Unable to read transport capabilities.");

                                    var dataEncoder = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) == 0)
                                        ? (IDataEncoder)Base64Encoder
                                        : PassThroughEncoder;

                                    var transferModeFeature = Features.Get <ITransferModeFeature>() ??
                                                              throw new InvalidOperationException("Unable to read transfer mode.");

                                    transferModeFeature.TransferMode =
                                        (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) != 0)
                                            ? TransferMode.Binary
                                            : TransferMode.Text;

                                    ProtocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder);
                                    _cachedPingMessage   = ProtocolReaderWriter.WriteMessage(PingMessage.Instance);

                                    Log.UsingHubProtocol(_logger, protocol.Name);

                                    UserIdentifier = userIdProvider.GetUserId(this);

                                    if (Features.Get <IConnectionInherentKeepAliveFeature>() == null)
                                    {
                                        // Only register KeepAlive after protocol negotiated otherwise KeepAliveTick could try to write without having a ProtocolReaderWriter
                                        Features.Get <IConnectionHeartbeatFeature>()?.OnHeartbeat(state => ((HubConnectionContext)state).KeepAliveTick(), this);
                                    }

                                    return(true);
                                }
                            }
                            else if (result.IsCompleted)
                            {
                                break;
                            }
                        }
                        finally
                        {
                            _connectionContext.Transport.Input.AdvanceTo(consumed, examined);
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Log.NegotiateCanceled(_logger);
            }

            return(false);
        }
コード例 #12
0
ファイル: HubMessage.cs プロジェクト: pardahlman/SignalR
 public SerializedMessage(HubProtocolReaderWriter protocolReaderWriter, byte[] message)
 {
     ProtocolReaderWriter = protocolReaderWriter;
     Message = message;
 }