public void GlobalSetup() { var arguments = new object[ArgumentCount]; for (var i = 0; i < arguments.Length; i++) { arguments[i] = "Hello world!"; } var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); _pipe = new TestDuplexPipe(); _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult)); } finally { MemoryBufferWriter.Return(writer); } _nextReadTcs = new TaskCompletionSource <ReadResult>(); _pipe.AddReadResult(new ValueTask <ReadResult>(_nextReadTcs.Task)); IHubProtocol hubProtocol; var hubConnectionBuilder = new HubConnectionBuilder(); if (Protocol == "json") { hubProtocol = new NewtonsoftJsonHubProtocol(); } else { hubProtocol = new MessagePackHubProtocol(); } hubConnectionBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHubProtocol), hubProtocol)); hubConnectionBuilder.WithUrl("http://doesntmatter"); _invocationMessageBytes = hubProtocol.GetMessageBytes(new InvocationMessage(MethodName, arguments)); var delegateConnectionFactory = new DelegateConnectionFactory(endPoint => { var connection = new DefaultConnectionContext(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; return(new ValueTask <ConnectionContext>(connection)); }); hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); _hubConnection = hubConnectionBuilder.Build(); _hubConnection.On(MethodName, arguments.Select(v => v.GetType()).ToArray(), OnInvoke); _hubConnection.StartAsync().GetAwaiter().GetResult(); }
public async Task HubConnectionClosesWithErrorIfTerminatedWithPartialMessage() { var builder = new HubConnectionBuilder(); var innerConnection = new TestConnection(); var delegateConnectionFactory = new DelegateConnectionFactory( format => innerConnection.StartAsync(format), connection => ((TestConnection)connection).DisposeAsync()); builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); var hubConnection = builder.Build(); var closedEventTcs = new TaskCompletionSource <Exception>(); hubConnection.Closed += e => { closedEventTcs.SetResult(e); return(Task.CompletedTask); }; await hubConnection.StartAsync().OrTimeout(); await innerConnection.Application.Output.WriteAsync(Encoding.UTF8.GetBytes(new[] { '{' })).OrTimeout(); innerConnection.Application.Output.Complete(); var exception = await closedEventTcs.Task.OrTimeout(); Assert.Equal("Connection terminated while reading a message.", exception.Message); }
public async Task StartingAfterStopCreatesANewConnection() { // Set up StartAsync to wait on the syncPoint when starting var createCount = 0; ValueTask <ConnectionContext> ConnectionFactory(EndPoint endPoint) { createCount += 1; return(new TestConnection().StartAsync()); } var builder = new HubConnectionBuilder().WithUrl("http://example.com"); var delegateConnectionFactory = new DelegateConnectionFactory(ConnectionFactory); builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); await AsyncUsing(builder.Build(), async connection => { Assert.Equal(HubConnectionState.Disconnected, connection.State); await connection.StartAsync().OrTimeout(); Assert.Equal(1, createCount); Assert.Equal(HubConnectionState.Connected, connection.State); await connection.StopAsync().OrTimeout(); Assert.Equal(HubConnectionState.Disconnected, connection.State); await connection.StartAsync().OrTimeout(); Assert.Equal(2, createCount); Assert.Equal(HubConnectionState.Connected, connection.State); }); }
public ClientService() { _settingsService ??= Locator.Current.GetService <ISettingsService>(); #if DEBUG if (_settingsService?.ChatServerPath == null) { return; } #endif var hubBuilder = new HubConnectionBuilder() .WithUrl(_settingsService.ChatServerPath) .AddNewtonsoftJsonProtocol(); if (_settingsService.WithReconnect) { hubBuilder = hubBuilder.WithAutomaticReconnect(); } _client = hubBuilder.Build(); _client.Closed += Closed; _client.Reconnected += Reconnected; _client.Reconnecting += Reconnecting; _client.On(ChatMethodType.RECEIVER, OnReceive); }
private async void Send() { if (string.IsNullOrEmpty(Message) || string.IsNullOrWhiteSpace(Message)) { Message = null; return; } if (App.hub.State == HubConnectionState.Disconnected) { var results = await App.client.GetStringAsync("https://naijaconnectfunction.azurewebsites.net/api/GetInfo"); var info = JsonConvert.DeserializeObject <ConnectionInfo>(results); var connectionBuilder = new HubConnectionBuilder(); connectionBuilder.WithUrl(info.Url, (Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionOptions obj) => { obj.AccessTokenProvider = () => Task.Run(() => info.AccessToken); }); App.hub = connectionBuilder.Build(); } var comment = new GroupMessage(Settings.UsernameSettings, Settings.KeySettings, GroupName, GroupId, Message.Trim()); var json = JsonConvert.SerializeObject(comment); var content = new StringContent(json, Encoding.UTF8, "application/json"); var result = await App.client.PostAsync("https://naijaconnectfunction.azurewebsites.net/api/SendGroupMessage", content); Message = string.Empty; }
public async Task ClientUsingOldCallWithOriginalProtocol(HttpTransportType transportType) { using (StartServer <VersionStartup>(out var loggerFactory, out var server, $"{nameof(ClientUsingOldCallWithOriginalProtocol)}_{transportType}")) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(loggerFactory) .WithUrl(server.Url + "/version", transportType); var connection = connectionBuilder.Build(); try { await connection.StartAsync().OrTimeout(); var result = await connection.InvokeAsync <string>(nameof(VersionHub.Echo), "Hello World!").OrTimeout(); Assert.Equal("Hello World!", result); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
private HubConnection buildConnection(CancellationToken cancellationToken) { var builder = new HubConnectionBuilder() .WithUrl(endpoint, options => { options.Headers.Add("Authorization", $"Bearer {api.AccessToken}"); options.Headers.Add("OsuVersionHash", versionHash); }); if (RuntimeInfo.SupportsJIT) { builder.AddMessagePackProtocol(); } else { // eventually we will precompile resolvers for messagepack, but this isn't working currently // see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308. builder.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); } var newConnection = builder.Build(); ConfigureConnection?.Invoke(newConnection); newConnection.Closed += ex => onConnectionClosed(ex, cancellationToken); return(newConnection); }
public async Task ExecuteAsync(Uri uri) { string circuitId = await GetPrerenderedCircuitId(uri); var builder = new HubConnectionBuilder(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>()); builder.WithUrl(new Uri(uri, "_blazor/")); builder.ConfigureLogging(l => l.AddConsole().SetMinimumLevel(LogLevel.Trace)); var hive = new ElementHive(); await using var connection = builder.Build(); await connection.StartAsync(CancellationToken); Console.WriteLine("Connected"); connection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS); connection.On <int, int, byte[]>("JS.RenderBatch", OnRenderBatch); connection.On <Error>("JS.OnError", OnError); connection.Closed += OnClosedAsync; // Now everything is registered so we can start the circuit. var success = await connection.InvokeAsync <bool>("ConnectCircuit", circuitId); await TaskCompletionSource.Task; void OnBeginInvokeJS(int asyncHandle, string identifier, string argsJson) { Console.WriteLine("JS Invoke: " + identifier + " (" + argsJson + ")"); } void OnRenderBatch(int browserRendererId, int batchId, byte[] batchData) { var batch = RenderBatchReader.Read(batchData); hive.Update(batch); // This will click the Counter component repeatedly resulting in infinite requests. _ = ClickAsync("thecounter", hive, connection); } void OnError(Error error) { Console.WriteLine("ERROR: " + error.Stack); } Task OnClosedAsync(Exception ex) { if (ex == null) { TaskCompletionSource.TrySetResult(null); } else { TaskCompletionSource.TrySetException(ex); } return(Task.CompletedTask); } }
public static async Task Main(string[] args) { string hubUrl = "https://localhost:5001/eventhub"; var builder = new HubConnectionBuilder().WithUrl(hubUrl); //Set connection var connection = builder.Build(); await connection.StartAsync(); using (var bus = RabbitHutch.CreateBus("host=localhost")) { bus.SubscribeAsync <EventMessage>("eventMessages", message => Task.Factory.StartNew(async() => { Console.WriteLine($"{message.EventName} {message.EventDescription}"); await connection.InvokeAsync <EventMessage>("EventMessageArrived", message); }).ContinueWith(task => { if (task.IsCompleted && !task.IsFaulted) { Console.WriteLine("Finished processing all messages"); } else { // Don't catch this, it is caught further up the hierarchy and results in being sent to the default error queue // on the broker throw new EasyNetQException( "Message processing exception - look in the default error queue (broker)"); } })); Console.WriteLine("Listening for messages. Hit <return> to quit."); Console.ReadLine(); } }
public static void Main() { Console.WriteLine("Hello SignalR!"); Console.ReadKey(); var token = GetApiKey(); var con = new HubConnectionBuilder() .WithUrl(@"https://*****:*****@"{timestamp} / {user} / {message}"); }); x.SendAsync("Register", "console").GetAwaiter().GetResult(); x.SendAsync("SendMessage", "Console", "Consoleeeee").GetAwaiter().GetResult(); Console.ReadKey(); }
private async void Form1_Load(object sender, EventArgs e) { var connection = new HubConnectionBuilder(); connection.WithUrl(url); _hub = connection.Build(); await _hub.StartAsync(); _hub.On <string, string>("ReceiveMessage", (user, message) => { new Thread(delegate() { ReceiveMessage(user, Newtonsoft.Json.JsonConvert.SerializeObject(message)); }).Start(); }); _hub.Closed += async(error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await _hub.StartAsync(); }; //_hub.On<object[]>("ReceiveMessage", (data) => //{ // new Thread(delegate () // { // Update(data); // }).Start(); //}); }
/// <summary> /// Initializes the proxy. /// </summary> /// <param name="hubPath">Hub server relative path.</param> /// <param name="serverUrl">Hub server URL.</param> public void Init(string hubPath = null, string serverUrl = null) { if (_connection != null) { Dispose(); } _hubPath = string.IsNullOrWhiteSpace(hubPath) ? HubPath : hubPath; _serverUrl = string.IsNullOrWhiteSpace(serverUrl) ? ServerUrl + _hubPath : serverUrl + _hubPath; var hubConnectionBuilder = new HubConnectionBuilder(); hubConnectionBuilder.Services.AddSingleton(BuildHubProtocol()); hubConnectionBuilder .WithUrl(_serverUrl) .WithAutomaticReconnect(RetryPolicy); if (ConnectionBuilder != null) { hubConnectionBuilder = ConnectionBuilder.Invoke(hubConnectionBuilder); } _connection = hubConnectionBuilder.Build(); _connection.Closed += OnConnectionClosed; _connection.Reconnecting += OnReconnecting; _connection.Reconnected += OnReconnected; _subs.Add(_connection.On <object[]>(nameof(IDotNetifyHubMethod.Response_VM), OnResponse_VM)); }
static async Task Main(string[] args) { string url = "http://localhost:2209/StubMessage"; HubConnectionBuilder hubConnectionBuilder = new HubConnectionBuilder(); hubConnectionBuilder.WithUrl(url); hubConnectionBuilder.WithAutomaticReconnect(); HubConnection hubConnection = hubConnectionBuilder.Build(); hubConnection.RegisterClosedHandler(); hubConnection.RegisterReconnectingHandler(); hubConnection.RegisterReconnectedHandler(); await hubConnection.StartAsync(); while (true) { Console.WriteLine("请输入消息标题!"); string title = Console.ReadLine(); Console.WriteLine("请输入消息内容!"); string content = Console.ReadLine(); StubMessage message = new StubMessage(title, content); await MessageMediator.SendAsync(hubConnection, message); Console.WriteLine("发送成功!"); Console.WriteLine("-------------------------------------"); } }
public Chat() { InitializeComponent(); HubConnectionBuilder builder = new HubConnectionBuilder() .WithUrl("http://192.168.1.19:5000/chatHub"); builder.Options.SkipNegotiation = true; _hubConnection = builder.Build(); _hubConnection.Closed += new EventHandler((s, m) => { Invoke(new Action(() => { AddMessages("Closed"); Connect.Text = "Connect"; SendButton.Enabled = false; })); Thread.Sleep(new Random().Next(0, 5) * 1000); _hubConnection.StartAsync(); }); _hubConnection.On <string, string>("ReceiveMessage", (user, message) => { var newMessage = $"{user}: {message}"; Invoke(new Action(() => { AddMessages(newMessage); })); }); SendButton.Enabled = false; }
public async Task CreateConnection() { await semaphoreSlim.WaitAsync(); if (httpClient == null) { httpClient = new HttpClient(); } var result = await httpClient.GetStringAsync("https://xamarinchatappfunctions.azurewebsites.net/api/GetSignalRInfo"); var info = JsonConvert.DeserializeObject <Models.ConnectionInfo>(result); var connectionBuilder = new HubConnectionBuilder(); connectionBuilder.WithUrl(info.Url, (Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionOptions obj) => { obj.AccessTokenProvider = () => Task.Run(() => info.AccessToken); }); hub = connectionBuilder.Build(); hub.On <object>("newMessage", (message) => { var json = message.ToString(); var obj = JsonConvert.DeserializeObject <Message>(json); var msg = (Message)JsonConvert.DeserializeObject(json, obj.TypeInfo); NewMessage?.Invoke(this, new NewMessageEventArgs(msg)); }); await hub.StartAsync(); IsConnected = true; semaphoreSlim.Release(); }
protected override async Task OnInitializedAsync() { HubConnectionBuilder factory = new HubConnectionBuilder(); factory.Services.AddLogging(builder => builder //.AddBrowserConsole() // Add Blazor.Extensions.Logging.BrowserConsoleLogger // This is not yet available for Blazor 0.8.0 https://github.com/BlazorExtensions/Logging/pull/22 .SetMinimumLevel(LogLevel.Trace) ); factory.WithUrlBlazor("/chathub", JsRuntime, options: opt => { //opt.Transports = HttpTransportType.WebSockets; //opt.SkipNegotiation = true; opt.AccessTokenProvider = async() => { var token = await this.GetJwtToken("DemoUser"); this.Logger.LogInformation($"Access Token: {token}"); return(token); }; }); this._connection = factory.Build(); this._connection.On <string>("Send", this.HandleTest); _connection.Closed += exception => { this.Logger.LogError(exception, "Connection was closed!"); return(Task.CompletedTask); }; await this._connection.StartAsync(); }
public void GlobalSetup() { var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); _handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); } finally { MemoryBufferWriter.Return(writer); } _pipe = new TestDuplexPipe(); var hubConnectionBuilder = new HubConnectionBuilder(); hubConnectionBuilder.WithUrl("http://doesntmatter"); var delegateConnectionFactory = new DelegateConnectionFactory(endPoint => { var connection = new DefaultConnectionContext(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; return(new ValueTask <ConnectionContext>(connection)); }); hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); _hubConnection = hubConnectionBuilder.Build(); }
public void GlobalSetup() { var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); _handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); } finally { MemoryBufferWriter.Return(writer); } _pipe = new TestDuplexPipe(); var connection = new TestConnection(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; var hubConnectionBuilder = new HubConnectionBuilder(); hubConnectionBuilder.WithHubProtocol(new JsonHubProtocol()); hubConnectionBuilder.WithConnectionFactory(() => connection); _hubConnection = hubConnectionBuilder.Build(); }
public async Task ClientUsingOldCallWithNewProtocol(HttpTransportType transportType) { using (var server = await StartServer <VersionStartup>()) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton <IHubProtocol>(new VersionedJsonHubProtocol(1000)); var connection = connectionBuilder.Build(); try { await connection.StartAsync().OrTimeout(); var result = await connection.InvokeAsync <string>(nameof(VersionHub.Echo), "Hello World!").OrTimeout(); Assert.Equal("Hello World!", result); } catch (Exception ex) { LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ClientWithUnsupportedProtocolVersionDoesNotConnect(HttpTransportType transportType) { bool ExpectedErrors(WriteContext writeContext) { return(writeContext.LoggerName == typeof(HubConnection).FullName); } using (var server = await StartServer <VersionStartup>(ExpectedErrors)) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton <IHubProtocol>(new VersionedJsonHubProtocol(int.MaxValue)); var connection = connectionBuilder.Build(); try { await ExceptionAssert.ThrowsAsync <HubException>( () => connection.StartAsync(), "Unable to complete handshake with the server due to an error: The server does not support version 2147483647 of the 'json' protocol.").OrTimeout(); } catch (Exception ex) { LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ClosedEventRaisedWhenTheClientIsStopped() { var builder = new HubConnectionBuilder(); var delegateConnectionFactory = new DelegateConnectionFactory( format => new TestConnection().StartAsync(format), connection => ((TestConnection)connection).DisposeAsync()); builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); var hubConnection = builder.Build(); var closedEventTcs = new TaskCompletionSource <Exception>(); hubConnection.Closed += e => { closedEventTcs.SetResult(e); return(Task.CompletedTask); }; await hubConnection.StartAsync().OrTimeout(); await hubConnection.StopAsync().OrTimeout(); Assert.Null(await closedEventTcs.Task); }
public async Task ObservingThoughApiWorks() { await Prepared.ConfigureAwait(false); var builder = new HubConnectionBuilder() .WithUrl($"http://test{LiveHub.Route}", cfg => cfg.HttpMessageHandlerFactory = _ => Server.CreateHandler()) ; var hubConnection = builder.Build(); await hubConnection.StartAsync(); var obs = hubConnection.Observe <ChangeData>(nameof(LiveHub.Observe)); const int takeCount = 10; var sem = new SemaphoreSlim(2); // Coordinate progress between produced data and listener var obsTask = obs .TraceTest(Output) .Take(takeCount) .Select((v, idx) => new { v, idx }) // Start a new producer whenever we have received 5 items .Do(x => { if (x.idx % 5 == 0) { sem.Release(); } }) .TraceTest(Output) .Select(x => x.v) .ToListAsync(CancellationToken); var pushTask = TestSource.ProduceData( // Wait for sem for each batch of data sem.ObserveRelease().Take(2).Select(_ => DateTime.UtcNow) .TraceTest(Output) ) .TraceTest(Output) .SelectMany(x => x) .TraceTest(Output) .ToListAsync(CancellationToken); // All ready, start pusing sem.Release(); var observedChanges = await obsTask.ConfigureAwait(false); var observed = observedChanges.Select(c => c.Entity).ToList(); var pushed = await pushTask.ConfigureAwait(false); var expect = pushed.Take(takeCount); observed.Should().BeEquivalentTo(expect, cfg => cfg.Excluding(x => x.Installation).Excluding(x => x.Signal)); // Reception should contained interleaved data observed.Select(x => x.InstallationId) .Should().NotBeAscendingInOrder() .And.NotBeDescendingInOrder(); }
static async Task VerifyCookie(string url, HttpTransportType transportType, bool addHandler) { var cookies = new CookieContainer(); var httpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, MaxConnectionsPerServer = 200000, MaxAutomaticRedirections = 200000, CookieContainer = cookies, }; var hubConnectionBuilder = new HubConnectionBuilder() .ConfigureLogging(logging => { logging.AddConsole(); }) .WithUrl(url, httpConnectionOptions => { if (addHandler) { httpConnectionOptions.HttpMessageHandlerFactory = _ => httpClientHandler; } httpConnectionOptions.Cookies = cookies; httpConnectionOptions.Transports = transportType; httpConnectionOptions.CloseTimeout = TimeSpan.FromMinutes(100); }); var connection = hubConnectionBuilder.Build(); var method = "echo"; var received = false; connection.On(method, (string uid, string time) => { Console.WriteLine($"receive {uid} {time}"); received = true; }); CancellationTokenSource closedTokenSource = null; connection.Closed += e => { // This should never be null by the time this fires closedTokenSource.Cancel(); Console.WriteLine("Connection closed..."); return(Task.CompletedTask); }; await Task.WhenAll(connection.StartAsync()); await connection.SendAsync(method, "abc", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); closedTokenSource = new CancellationTokenSource(); while (!received && !closedTokenSource.Token.IsCancellationRequested) { await Task.Delay(1000); Console.WriteLine("Waiting for result"); } closedTokenSource?.Dispose(); }
public async Task ClientUsingNewCallWithNewProtocol(HttpTransportType transportType) { await using (var server = await StartServer <VersionStartup>()) { var httpConnectionFactory = new HttpConnectionFactory( Options.Create(new HttpConnectionOptions { Transports = transportType, DefaultTransferFormat = TransferFormat.Text }), LoggerFactory); var tcs = new TaskCompletionSource(); var proxyConnectionFactory = new ProxyConnectionFactory(httpConnectionFactory); var connectionBuilder = new HubConnectionBuilder() .WithUrl(new Uri(server.Url + "/version")) .WithLoggerFactory(LoggerFactory); connectionBuilder.Services.AddSingleton <IHubProtocol>(new VersionedJsonHubProtocol(1000)); connectionBuilder.Services.AddSingleton <IConnectionFactory>(proxyConnectionFactory); var connection = connectionBuilder.Build(); connection.On("NewProtocolMethodClient", () => { tcs.SetResult(); }); try { await connection.StartAsync().DefaultTimeout(); // Task should already have been awaited in StartAsync var connectionContext = await proxyConnectionFactory.ConnectTask.DefaultTimeout(); // Simulate a new call from the client var messageToken = new JObject { ["type"] = int.MaxValue }; connectionContext.Transport.Output.Write(Encoding.UTF8.GetBytes(messageToken.ToString())); connectionContext.Transport.Output.Write(new[] { (byte)0x1e }); await connectionContext.Transport.Output.FlushAsync().DefaultTimeout(); await tcs.Task.DefaultTimeout(); } catch (Exception ex) { LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } }
public async Task <bool> ConnectAsync(Uri uri, bool connectAutomatically = true, Action <HubConnectionBuilder, Uri>?configure = null) { var builder = new HubConnectionBuilder(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>()); var hubUrl = GetHubUrl(uri); builder.WithUrl(hubUrl); builder.ConfigureLogging(l => { l.SetMinimumLevel(LogLevel.Trace); if (LoggerProvider != null) { l.AddProvider(LoggerProvider); } }); configure?.Invoke(builder, hubUrl); _hubConnection = builder.Build(); HubConnection.On <int, string>("JS.AttachComponent", OnAttachComponent); HubConnection.On <int, string, string, int, long>("JS.BeginInvokeJS", OnBeginInvokeJS); HubConnection.On <string>("JS.EndInvokeDotNet", OnEndInvokeDotNet); HubConnection.On <int, byte[]>("JS.RenderBatch", OnRenderBatch); HubConnection.On <string>("JS.Error", OnError); HubConnection.Closed += OnClosedAsync; for (var i = 0; i < 10; i++) { try { await HubConnection.StartAsync(CancellationToken); break; } catch { await Task.Delay(500); // Retry 10 times } } if (!connectAutomatically) { return(true); } var descriptors = await GetPrerenderDescriptors(uri); await ExpectRenderBatch( async() => CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", uri, uri, descriptors, null, CancellationToken), DefaultConnectionTimeout); return(CircuitId != null); }
static async Task Main(string[] args) { var url = "http://localhost:5000/benchmark"; var transportType = HttpTransportType.WebSockets; // var transportType = HttpTransportType.ServerSentEvents; // var transportType = HttpTransportType.LongPolling; var hubConnectionBuilder = new HubConnectionBuilder() .WithUrl(url, httpConnectionOptions => { // set transport type httpConnectionOptions.Transports = transportType; }); if (useMessagePack) { hubConnectionBuilder.AddMessagePackProtocol(); } var connection = hubConnectionBuilder.Build(); await connection.StartAsync(); Console.WriteLine($"Starting connection with transport type {transportType}. Press Ctrl-C to close."); var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, a) => { a.Cancel = true; cts.Cancel(); }; connection.Closed += e => { if (e != null) { Console.WriteLine("Connection closed with error: {0}", e); } else { Console.WriteLine("Connection closed"); } cts.Cancel(); return(Task.CompletedTask); }; connection.On("echo", (string name, string message) => { Console.WriteLine($"INFO: server -> client: {name}: {message}"); }); await connection.InvokeAsync <string>("Echo", "albert", "hello"); await connection.StopAsync(); }
public void GlobalSetup() { var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); _pipe = new TestDuplexPipe(); _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult)); } finally { MemoryBufferWriter.Return(writer); } _tcs = new TaskCompletionSource <ReadResult>(); _pipe.AddReadResult(new ValueTask <ReadResult>(_tcs.Task)); var hubConnectionBuilder = new HubConnectionBuilder(); if (Protocol == "json") { // JSON protocol added by default } else { hubConnectionBuilder.AddMessagePackProtocol(); } var delegateConnectionFactory = new DelegateConnectionFactory(format => { var connection = new DefaultConnectionContext(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; return(Task.FromResult <ConnectionContext>(connection)); }, connection => { connection.Transport.Output.Complete(); connection.Transport.Input.Complete(); return(Task.CompletedTask); }); hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); _hubConnection = hubConnectionBuilder.Build(); _hubConnection.StartAsync().GetAwaiter().GetResult(); _arguments = new object[ArgumentCount]; for (var i = 0; i < _arguments.Length; i++) { _arguments[i] = "Hello world!"; } }
public void CannotCreateConnectionWithNoEndPoint() { var builder = new HubConnectionBuilder(); builder.Services.AddSingleton <IConnectionFactory>(new HttpConnectionFactory(Options.Create(new HttpConnectionOptions()), NullLoggerFactory.Instance)); var ex = Assert.Throws <InvalidOperationException>(() => builder.Build()); Assert.Equal("Cannot create HubConnection instance. An EndPoint was not configured.", ex.Message); }
private HubConnection CreateHubConnection(Func <TransferFormat, Task <ConnectionContext> > connectDelegate, Func <ConnectionContext, Task> disposeDelegate) { var builder = new HubConnectionBuilder(); var delegateConnectionFactory = new DelegateConnectionFactory(connectDelegate, disposeDelegate); builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); return(builder.Build()); }
private static HubConnection CreateConnection(string url, HttpTransportType transportType, IHubProtocol protocol, ILoggerFactory loggerFactory) { var hubConnectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(loggerFactory) .WithUrl(url, transportType); hubConnectionBuilder.Services.AddSingleton(protocol); return(hubConnectionBuilder.Build()); }