static async Task RunAsync(string endpoint, int port, string prefix, ChannelOption[] options) { var channel = new Channel(endpoint, port, ChannelCredentials.Insecure, options); var client = MagicOnionClient.Create <IEchoService>(new DefaultCallInvoker(channel)); var reply = await client.EchoAsync("hogemoge"); Console.WriteLine("Echo: " + reply); // duplex var receiver = new MyHubReceiver(); var hubClient = await StreamingHubClient.ConnectAsync <IMyHub, IMyHubReceiver>(new DefaultCallInvoker(channel), receiver); var roomPlayers = await hubClient.JoinAsync($"room {prefix}", "hoge"); foreach (var player in roomPlayers) { receiver.OnJoin(player); } var i = 0; while (i++ < 100) { await hubClient.SendAsync($"{prefix} {i}"); await Task.Delay(TimeSpan.FromSeconds(60)); } await hubClient.LeaveAsync(); await hubClient.DisposeAsync(); await channel.ShutdownAsync(); }
private async Task InitializeClientAsync() { // Initialize the Hub // NOTE: If you want to use SSL/TLS connection, see InitialSettings.OnRuntimeInitialize method. this.channel = GrpcChannelx.ForAddress("http://localhost:5000"); while (!shutdownCancellation.IsCancellationRequested) { try { Debug.Log($"Connecting to the server..."); this.streamingClient = await StreamingHubClient.ConnectAsync <IChatHub, IChatHubReceiver>(this.channel, this, cancellationToken : shutdownCancellation.Token); this.RegisterDisconnectEvent(streamingClient); Debug.Log($"Connection is established."); break; } catch (Exception e) { Debug.LogError(e); } Debug.Log($"Failed to connect to the server. Retry after 5 seconds..."); await Task.Delay(5 * 1000); } this.client = MagicOnionClient.Create <IChatService>(this.channel); }
private async Task InitializeClientAsync() { // Initialize the Hub this.channel = new Channel("localhost", 5000, ChannelCredentials.Insecure); // for SSL/TLS connection //var cred = new SslCredentials(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "server.crt"))); //this.channel = new Channel("dummy.example.com", 5000, cred); // local tls //this.channel = new Channel("your-nlb-domain.com", 5000, new SslCredentials()); // aws nlb tls while (!shutdownCancellation.IsCancellationRequested) { try { Debug.Log($"Connecting to the server..."); this.streamingClient = await StreamingHubClient.ConnectAsync <IChatHub, IChatHubReceiver>(this.channel, this, cancellationToken : shutdownCancellation.Token); this.RegisterDisconnectEvent(streamingClient); Debug.Log($"Connection is established."); break; } catch (Exception e) { Debug.LogError(e); } Debug.Log($"Failed to connect to the server. Retry after 5 seconds..."); await Task.Delay(5 * 1000); } this.client = MagicOnionClient.Create <IChatService>(this.channel); }
/// <summary> /// 接続開始 /// </summary> /// <param name="receiver"></param> /// <param name="ipAddr"></param> /// <param name="port"></param> /// <returns></returns> public async UniTask ConnectStartAsync() { while (!cancellationTokenSource.IsCancellationRequested) { try { // 本当にサーバーに接続できるか確認 await channel.ConnectAsync(DateTime.UtcNow.AddSeconds(5)); Debug.Log("connecting to the server ... "); ServerImpl = await StreamingHubClient.ConnectAsync <TServer, TClient>(channel, ClientImpl, cancellationToken : cancellationTokenSource.Token); executeDisconnectEventWaiterAsync(ServerImpl).Forget(); Debug.Log("established connect"); break; } catch (TaskCanceledException) { } catch (OperationCanceledException e) { Debug.LogWarning(e); throw new OperationCanceledException(); } catch (Exception e) { Debug.LogError(e); } Debug.Log("Retry after 2 seconds"); await UniTask.Delay(2 * 1000, cancellationToken : cancellationTokenSource.Token); } }
public async Task Connect() { channel = GrpcChannel.ForAddress(address); serviceClient = MagicOnionClient.Create <ITodoService>(channel); notifyClient = await StreamingHubClient.ConnectAsync <ITodoNotify, ITodoNotifyReceiver>(channel, this); await notifyClient.Join(); manager = new TodoManager(await serviceClient.Get()); }
private async Task InitializeClientAsync() { // If you want configure KEEP_ALIVE interval, then.... // * set same value for `grpc.keepalive_time_ms` and `grpc.http2.min_time_between_pings_ms` // * keep `grpc.http2.min_ping_interval_without_data_ms < grpc.http2.min_time_between_pings_ms` var options = new[] { // send keepalive ping every 10 second, default is 2 hours new ChannelOption("grpc.keepalive_time_ms", 10000), // keepalive ping time out after 5 seconds, default is 20 seoncds new ChannelOption("grpc.keepalive_timeout_ms", 5000), // allow grpc pings from client every 10 seconds new ChannelOption("grpc.http2.min_time_between_pings_ms", 10000), // allow unlimited amount of keepalive pings without data new ChannelOption("grpc.http2.max_pings_without_data", 0), // allow keepalive pings when there's no gRPC calls new ChannelOption("grpc.keepalive_permit_without_calls", 1), // allow grpc pings from client without data every 5 seconds new ChannelOption("grpc.http2.min_ping_interval_without_data_ms", 5000), }; // Initialize the Hub channel = new Channel("localhost", 5000, ChannelCredentials.Insecure, options); // for SSL/TLS connection // var cred = new SslCredentials(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "server.crt"))); // channel = new Channel("dummy.example.com", 5000, cred, options); // local tls // channel = new Channel("your-nlb-domain.com", 5000, new SslCredentials()); // aws nlb tls while (!shutdownCancellation.IsCancellationRequested) { try { Debug.Log($"Connecting to the server..."); streamingClient = await StreamingHubClient.ConnectAsync <IChatHub, IChatHubReceiver>(channel, this, cancellationToken : shutdownCancellation.Token); RegisterDisconnectEvent(streamingClient); Debug.Log($"Connection is established."); break; } catch (Exception e) { Debug.LogError(e); } Debug.Log($"Failed to connect to the server. Retry after 5 seconds..."); await Task.Delay(5 * 1000); } client = MagicOnionClient.Create <IChatService>(channel); }
static async Task RunAsync(string endpoint, string prefix) { var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan, // grpc.keepalive_time_ms KeepAlivePingDelay = TimeSpan.FromSeconds(10), // grpc.keepalive_timeout_ms KeepAlivePingTimeout = TimeSpan.FromSeconds(10), // grpc.keepalive_permit_without_calls: 1 = Always KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, EnableMultipleHttp2Connections = true }, }); var client = MagicOnionClient.Create <IEchoService>(channel); var reply = await client.EchoAsync("hogemoge"); Console.WriteLine("Echo: " + reply); // duplex var receiver = new MyHubReceiver(); var hubClient = await StreamingHubClient.ConnectAsync <IMyHub, IMyHubReceiver>(channel, receiver); var roomPlayers = await hubClient.JoinAsync($"room {prefix}", "hoge"); foreach (var player in roomPlayers) { receiver.OnJoin(player); } var i = 0; while (i++ < 100) { await hubClient.SendAsync($"{prefix} {i}"); await Task.Delay(TimeSpan.FromSeconds(60)); } await hubClient.LeaveAsync(); await hubClient.DisposeAsync(); await channel.ShutdownAsync(); }
private async Task ReconnectServerAsync() { Debug.Log($"Reconnecting to the server..."); this.streamingClient = await StreamingHubClient.ConnectAsync <IChatHub, IChatHubReceiver>(this.channel, this); this.RegisterDisconnectEvent(streamingClient); Debug.Log("Reconnected."); this.JoinOrLeaveButton.interactable = true; this.SendMessageButton.interactable = false; this.SendReportButton.interactable = true; this.DisconnectButon.interactable = true; this.ExceptionButton.interactable = true; this.UnaryExceptionButton.interactable = true; this.isSelfDisConnected = false; }
public async Task <GameObject> ConnectAsync(Channel grpcChannel, string roomName, string playerName) { Debug.Log("aaaa"); this.gamingHub = await StreamingHubClient.ConnectAsync <IGamingHub, IGamingHubReceiver>(grpcChannel, this); // var roomPlayers = await gamingHub.JoinAsync(roomName, playerName, Vector3.zero, Quaternion.identity); foreach (var player in roomPlayers) { if (player.Name != playerName) { (this as IGamingHubReceiver).OnJoin(player); } } return(players[playerName]); }
public async ValueTask RunAsync(CancellationToken cancellationToken = default) { var capabilitis = new List <string>(); var interfaces = typeof(T).GetInterfaces().Select(type => type.FullName).ToHashSet(); if (interfaces.Contains(typeof(ImportPlugin).FullName)) { capabilitis.Add(typeof(ImportPlugin).FullName); } var capability = new Capability { Capabilities = capabilitis }; var grpcChannel = GrpcChannel.ForAddress(address); client = await StreamingHubClient.ConnectAsync <IGamingHub, IGamingHubReceiver>(grpcChannel, this); instanceId = await client.RegisterPlugin(capability); await Task.Delay(TimeSpan.FromMilliseconds(-1), cancellationToken); }
public CCoreHubLongRunBenchmarkScenario(Channel[] channels, BenchReporter reporter, BenchmarkerConfig config) { _clients = channels.Select(x => StreamingHubClient.ConnectAsync <ILongRunBenchmarkHub, ILongRunBenchmarkHubReciever>(new DefaultCallInvoker(x), this).GetAwaiter().GetResult()).ToArray(); _reporter = reporter; _config = config; }
public override async Task SetupAsync(WorkloadContext context) { channel = GrpcChannel.ForAddress("http://localhost:5059"); client = await StreamingHubClient.ConnectAsync <IEchoHub, IEchoHubReceiver>(channel, this); }
private async Task MainCore(string[] args) { var channel = GrpcChannel.ForAddress("https://*****:*****@"[IAccountService.GetCurrentUserNameAsync] Current User: UserId={user.UserId}; IsAuthenticated={user.IsAuthenticated}; Name={user.Name}"); try { var greeterClientAnon = MagicOnionClient.Create <IGreeterService>(channel); Console.WriteLine($"[IGreeterService.HelloAsync] {await greeterClientAnon.HelloAsync()}"); } catch (RpcException e) { Console.WriteLine($"[IGreeterService.HelloAsync] Exception: {e.Message}"); } } // 3. Sign-in with ID and password and receive an authentication token. (WithAuthenticationFilter will acquire an authentication token automatically.) var signInId = "*****@*****.**"; var password = "******"; // 4. Get the user information using the authentication token. { var accountClient = MagicOnionClient.Create <IAccountService>(channel, new[] { new WithAuthenticationFilter(signInId, password, channel), }); var user = await accountClient.GetCurrentUserNameAsync(); Console.WriteLine($@"[IAccountService.GetCurrentUserNameAsync] Current User: UserId={user.UserId}; IsAuthenticated={user.IsAuthenticated}; Name={user.Name}"); // 5. Call an API with the authentication token. var greeterClient = MagicOnionClient.Create <IGreeterService>(channel, new[] { new WithAuthenticationFilter(signInId, password, channel), }); Console.WriteLine($"[IGreeterService.HelloAsync] {await greeterClient.HelloAsync()}"); } // 5. Call StreamingHub with authentication { var timerHubClient = await StreamingHubClient.ConnectAsync <ITimerHub, ITimerHubReceiver>( channel, this, option : new CallOptions().WithHeaders(new Metadata() { { "Authorization", "Bearer " + AuthenticationTokenStorage.Current.Token } })); await timerHubClient.SetAsync(TimeSpan.FromSeconds(5)); await Task.Yield(); // NOTE: Release the gRPC's worker thread here. } // 6. Insufficient privilege (The current user is not in administrators role). { var accountClient = MagicOnionClient.Create <IAccountService>(channel, new[] { new WithAuthenticationFilter(signInId, password, channel), }); try { await accountClient.DangerousOperationAsync(); } catch (Exception e) { Console.WriteLine($"[IAccountService.DangerousOperationAsync] Exception: {e.Message}"); } } // 7. Refresh the token before calling an API. { await Task.Delay(1000 * 6); // The server is configured a token expiration set to 5 seconds. var greeterClient = MagicOnionClient.Create <IGreeterService>(channel, new[] { new WithAuthenticationFilter(signInId, password, channel), }); Console.WriteLine($"[IGreeterService.HelloAsync] {await greeterClient.HelloAsync()}"); } Console.ReadLine(); }
public HubBenchmarkScenario(GrpcChannel[] channels, BenchReporter reporter, BenchmarkerConfig config) { _clients = channels.Select(x => StreamingHubClient.ConnectAsync <IBenchmarkHub, IBenchmarkHubReciever>(x, this).GetAwaiter().GetResult()).ToArray(); _reporter = reporter; _config = config; }