Exemplo n.º 1
1
        public void Init()
        {
            var serverCredentials = new SslServerCredentials(new[] { new KeyCertificatePair(File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerPrivateKeyPath)) });
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            var asyncAuthInterceptor = new AsyncAuthInterceptor(async (authUri, metadata) =>
            {
                await Task.Delay(100);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });

            var clientCredentials = ChannelCredentials.Create(
                new SslCredentials(File.ReadAllText(TestCredentials.ClientCertAuthorityPath)),
                new MetadataCredentials(asyncAuthInterceptor));
            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client = TestService.NewClient(channel);
        }
Exemplo n.º 2
0
        public async Task <string[]> GenerateSeed(string aezeedPassphrase = default(string))
        {
            var genSeedResponse = new GenSeedResponse();

            try
            {
                walletRpcChannel = new Grpc.Core.Channel(HostName, new SslCredentials(Cert));
                walletUnlocker   = new WalletUnlocker.WalletUnlockerClient(walletRpcChannel);
                await walletRpcChannel.ConnectAsync();

                var genSeedRequest = new GenSeedRequest();
                if (!string.IsNullOrEmpty(aezeedPassphrase))
                {
                    genSeedRequest.AezeedPassphrase = ByteString.CopyFromUtf8(aezeedPassphrase);
                }
                genSeedResponse = await walletUnlocker.GenSeedAsync(genSeedRequest);

                walletRpcChannel.ShutdownAsync().Wait();
            } catch (RpcException e)
            {
                walletRpcChannel.ShutdownAsync().Wait();
                return(new string[] { e.Status.Detail });
            }
            return(genSeedResponse.CipherSeedMnemonic.ToArray());;
        }
Exemplo n.º 3
0
 public void Connect()
 {
     this.channel          = new grpc.Channel(host, port, grpc.ChannelCredentials.Insecure);
     this.client           = new EdgifyService.EdgifyServiceClient(channel);
     this.analytics_client = new AnalyticsService.AnalyticsServiceClient(channel);
     this.samples_client   = new SamplesService.SamplesServiceClient(channel);
 }
        private const string ProjectName = "apiarydotnetclienttesting"; // this is actually gRPC, but I had that project handy

        #endregion Fields

        #region Methods

        static void Main(string[] args)
        {
            // Prerequisites
            // 1. create a new cloud project with your google account
            // 2. enable cloud datastore API on that project
            // 3. 'gcloud auth login' to store your google credential in a well known location (from where GoogleCredential.GetApplicationDefaultAsync() can pick it up).

            var credentials = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;

            Channel channel = new Channel("datastore.googleapis.com", credentials.ToChannelCredentials());

            var datastoreClient = new Google.Datastore.V1Beta3.Datastore.DatastoreClient(channel);

            var result = datastoreClient.RunQuery(new RunQueryRequest
            {
                ProjectId = ProjectName,
                GqlQuery = new GqlQuery {
                    QueryString = "SELECT * FROM Foo"
                }
            });

            Console.WriteLine(result);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            channel.ShutdownAsync();
        }
Exemplo n.º 5
0
        public async Task <IActionResult> OnPost()
        {
            using var ms1 = new MemoryStream();
            await PhotoFile.CopyToAsync(ms1);

            ms1.Position = 0;

            var model = new Application.Posts.Models.PostAddModel
            {
                Body   = this.Body,
                UserId = ""
            };

            var postId = await _postService.Create(model);

            var userId = User.GetUserId();

            #region Upload to Vega

            var channel = new Grpc.Core.Channel("localhost:5005", SslCredentials.Insecure);
            var client  = new Servers.Vega.FileService.FileServiceClient(channel);

            var result2 = client.UploadFile(new UploadRequest
            {
                Content     = ByteString.CopyFrom(ms1.ToArray()),
                ContentType = PhotoFile.ContentType,
                Name        = PhotoFile.FileName,
                PostId      = postId,
                UserId      = User.GetUserId()
            });
            #endregion

            return(RedirectToPage("/index"));
        }
Exemplo n.º 6
0
        public LndGrpcService(IConfiguration config)
        {
            /*
             * var certLoc = config.GetValue<string>("cert");
             * var macLoc = config.GetValue<string>("mac");
             * ;
             *
             * var directory = Path.GetFullPath(certLoc);
             * Console.WriteLine(rpc + " stuff " + directory);*/
            var directory = Environment.CurrentDirectory;
            var tls       = File.ReadAllText(directory + "./../lnd-test-cluster/docker/temp/lnd-alice/tls.cert");
            var hexMac    = Util.ToHex(File.ReadAllBytes(directory + "./../lnd-test-cluster/docker/temp/lnd-alice/data/chain/bitcoin/regtest/admin.macaroon"));
            var rpc       = config.GetValue <string>("rpc");

            feePercentage    = config.GetValue <uint>("fee");
            maxSatPerPayment = config.GetValue <uint>("max_sat");
            maxVouchers      = config.GetValue <uint>("max_voucher");
            var macaroonCallCredentials = new MacaroonCallCredentials(hexMac);
            var channelCreds            = ChannelCredentials.Create(new SslCredentials(tls), macaroonCallCredentials.credentials);
            var lndChannel = new Grpc.Core.Channel(rpc, channelCreds);

            client  = new Lightning.LightningClient(lndChannel);
            getInfo = client.GetInfo(new GetInfoRequest());
            Console.WriteLine(getInfo.ToString());
        }
Exemplo n.º 7
0
 // Creates a client to Juzusvr with SSL credentials
 // from a string containing PEM encoded root certificates,
 // that can validate the certificate presented by the server.
 public Client(string url, string rootCert)
 {
     this.serverURL = url;
     this.creds     = new Grpc.Core.SslCredentials(rootCert);
     this.channel   = new Grpc.Core.Channel(url, this.creds, this.defaultChannelOptions());
     this.client    = client = new CobaltSpeech.Juzu.Juzu.JuzuClient(channel);
 }
Exemplo n.º 8
0
 public void State_IdleAfterCreation()
 {
     using (var channel = new Channel("localhost", Credentials.Insecure))
     {
         Assert.AreEqual(ChannelState.Idle, channel.State);
     }
 }
Exemplo n.º 9
0
        public async Task ManyStreamingServerCallsSingleClientTest()
        {
            GrpcCore.Server server = this.StartSimpleServiceServer();

            GrpcCore.Channel channel = new GrpcCore.Channel($"127.0.0.1:{GrpcTestPort}", GrpcCore.ChannelCredentials.Insecure);
            var client = new SimpleCoreService.SimpleCoreServiceClient(channel);

            List <Task> activeCalls      = new List <Task>();
            const int   TotalClientCalls = 100;
            const int   ClientId         = 0;
            TaskCompletionSource <bool> tasksQueuedCompletionSource = new TaskCompletionSource <bool>();

            var callsCounter = new CallsCounter {
                nTotalCalls = TotalClientCalls, tasksQueueTask = tasksQueuedCompletionSource.Task
            };

            this.activeCallCountersDictionary.Add(ClientId, callsCounter);

            for (int i = 0; i < 100; i++)
            {
                activeCalls.Add(MakeStreamingServerCalls(client, ClientId, 10, 10));
                lock (callsCounter)
                {
                    callsCounter.nActiveCalls++;
                }
            }
            Assert.AreEqual(TotalClientCalls, callsCounter.nActiveCalls);
            tasksQueuedCompletionSource.SetResult(true);

            await Task.WhenAll(activeCalls);

            Assert.AreEqual(0, callsCounter.nActiveCalls);

            await server.ShutdownAsync();
        }
Exemplo n.º 10
0
 public void Init()
 {
     helper = new MockServiceHelper(Host);
     server = helper.GetServer();
     server.Start();
     channel = helper.GetChannel();
 }
Exemplo n.º 11
0
 public void Init()
 {
     var marshaller = new Marshaller<string>(
         (str) =>
         {
             if (str == "UNSERIALIZABLE_VALUE")
             {
                 // Google.Protobuf throws exception inherited from IOException
                 throw new IOException("Error serializing the message.");
             }
             return System.Text.Encoding.UTF8.GetBytes(str); 
         },
         (payload) =>
         {
             var s = System.Text.Encoding.UTF8.GetString(payload);
             if (s == "UNPARSEABLE_VALUE")
             {
                 // Google.Protobuf throws exception inherited from IOException
                 throw new IOException("Error parsing the message.");
             }
             return s;
         });
     helper = new MockServiceHelper(Host, marshaller);
     server = helper.GetServer();
     server.Start();
     channel = helper.GetChannel();
 }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            var rpcChannel = new Channel("localhost:1337", ChannelCredentials.Insecure);
            var rpcClient = new BenchmarkServiceClient(BenchmarkService.NewClient(rpcChannel));
            rpcChannel.ConnectAsync().Wait();

            _timer.Elapsed += (s, e) =>
            {
                var lastMinuteCallCount = Interlocked.Exchange(ref _lastMinuteCallCount, 0);
                Console.WriteLine($"{DateTime.Now} -- {lastMinuteCallCount} ops/sec");
            };
            _timer.Start();

            for (int i = 0; i < CALL_COUNT; i++)
            {
                rpcClient.Operation(new ServiceRequest { Id = 10 });
                Interlocked.Increment(ref _lastMinuteCallCount);
            }

            //for (int i = 0; i < CALL_COUNT; i++)
            //{
            //    rpcClient.OperationAsync(new ServiceRequest { Id = 10 }).ContinueWith(t => Interlocked.Increment(ref _lastMinuteCallCount));
            //}

            //rpcClient.OperationStreamAsync(() => Interlocked.Increment(ref _lastMinuteCallCount)).Wait();
        }
Exemplo n.º 13
0
        public List <VoiceItem> ListVoices(Grpc.Core.Channel channel)
        {
            TextToSpeechClient client = TextToSpeechClient.Create(channel);

            // Performs the list voices request
            var response = client.ListVoices(new ListVoicesRequest
            {
            });

            List <VoiceItem> voices = new List <VoiceItem>();

            foreach (Voice voice in response.Voices)
            {
                foreach (var languageCode in voice.LanguageCodes)
                {
                    VoiceItem voiceItem = new VoiceItem
                    {
                        Name     = voice.Name,
                        Gender   = voice.SsmlGender.ToString(),
                        Language = languageCode,
                    };
                    voices.Add(voiceItem);
                }
            }
            return(voices);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            // initialization, better done elsewhere
            var channel = new Grpc.Core.Channel("localhost", 5000, ChannelCredentials.Insecure);

            //// create client
            //var customerClient = new Customer.CustomerClient(channel);
            //var customerRequested = new IsProductAddressUpdateAllowedRequest
            //{
            //    StateFrom = "ON",
            //    StateTo = "OW",
            //    Userrelationid = 1234
            //};

            //var response = customerClient.IsProductAddressUpdateAllowed(customerRequested);

            //Console.WriteLine(response.IsAddressUpdatable.ToString());
            //Console.WriteLine(response.ReturnMessage);

            var client = new ShoppingCart.ShoppingCartClient(channel); // Customer.CustomerClient(channel);

            var request = new InsuranceTrialLinkGetRequest
            {
                State  = "SC",
                Server = 1
            };

            var reply = client.InsuranceTrialLinkGet(request);

            Console.WriteLine(reply.TrialURL.ToString());
            Console.ReadLine();

            Console.ReadKey();
        }
Exemplo n.º 15
0
 public void Target()
 {
     using (var channel = new Channel("127.0.0.1", Credentials.Insecure))
     {
         Assert.IsTrue(channel.Target.Contains("127.0.0.1"));
     }
 }
Exemplo n.º 16
0
        public void test()
        {
            LanguageServiceSettings settings = new LanguageServiceSettings();

            if (TimeOut > 0)
            {
                int hour = TimeOut / 3600;
                int min  = TimeOut / 60;
                if (TimeOut >= 60)
                {
                    TimeOut = TimeOut % 60;
                }
                TimeSpan ts0 = new TimeSpan(hour, min, TimeOut);
                settings.AnalyzeSentimentSettings = CallSettings.FromCallTiming(CallTiming.FromTimeout(ts0));
            }
            string json       = "{\"type\": \"service_account\",\"project_id\": \"" + Config["project_id"] + "\",\"private_key_id\": \"" + Config["private_key_id"] + "\",\"private_key\": \"" + Config["private_key"] + "\",\"client_email\": \"" + Config["client_email"] + "\",\"client_id\": \"" + Config["client_id"] + "\",\"auth_uri\": \"" + Config["auth_uri"] + "\",\"token_uri\": \"" + Config["token_uri"] + "\",\"auth_provider_x509_cert_url\": \"" + Config["auth_provider_x509_cert_url"] + "\",\"client_x509_cert_url\": \"" + Config["client_x509_cert_url"] + "\"}";
            var    credential = GoogleCredential.FromJson(json).CreateScoped(LanguageServiceClient.DefaultScopes);
            var    channel    = new Grpc.Core.Channel(
                LanguageServiceClient.DefaultEndpoint.ToString(),
                credential.ToChannelCredentials());
            LanguageServiceClient test = LanguageServiceClient.Create(channel, settings);
            var Sentimentresponse      = test.AnalyzeSentiment(new Document()
            {
                Content = "hello",
                Type    = Document.Types.Type.PlainText
            });
        }
Exemplo n.º 17
0
 private async static void TestStream(string server)
 {
     while (true)
     {
         var channel = new Grpc.Core.Channel(server, ChannelCredentials.Insecure);
         var client  = new RouteGuideClient(channel);
         using (var call = client.ListFeatures(new Rectangle()))
         {
             try
             {
                 while (await call.ResponseStream.MoveNext())
                 {
                     Feature feature = call.ResponseStream.Current;
                     Console.WriteLine($"Received {feature}");
                 }
                 break;
             }
             catch (Exception ex)
             {
                 Console.WriteLine($"{ex.Message}");
                 System.Threading.Thread.Sleep(1000);
                 ; // loop
             }
         }
         channel.ShutdownAsync().Wait();
     }
     Console.WriteLine("Finished TestStream");
 }
Exemplo n.º 18
0
 public void WaitForStateChangedAsync_InvalidArgument()
 {
     using (var channel = new Channel("localhost", Credentials.Insecure))
     {
         Assert.Throws(typeof(ArgumentException), () => channel.WaitForStateChangedAsync(ChannelState.FatalFailure));
     }
 }
Exemplo n.º 19
0
        public static async Task<WalletClient> ConnectAsync(string networkAddress, string rootCertificate)
        {
            if (networkAddress == null)
                throw new ArgumentNullException(nameof(networkAddress));
            if (rootCertificate == null)
                throw new ArgumentNullException(nameof(rootCertificate));

            var channel = new Channel(networkAddress, new SslCredentials(rootCertificate));
            var deadline = DateTime.UtcNow.AddSeconds(3);
            try
            {
                await channel.ConnectAsync(deadline);
            }
            catch (TaskCanceledException)
            {
                await channel.ShutdownAsync();
                throw new ConnectTimeoutException();
            }

            // Ensure the server is running a compatible version.
            var versionClient = new VersionService.VersionServiceClient(channel);
            var response = await versionClient.VersionAsync(new VersionRequest(), deadline: deadline);
            var serverVersion = new SemanticVersion(response.Major, response.Minor, response.Patch);
            SemanticVersion.AssertCompatible(RequiredRpcServerVersion, serverVersion);

            return new WalletClient(channel);
        }
Exemplo n.º 20
0
        public void Init()
        {
            var rootCert = File.ReadAllText(TestCredentials.ClientCertAuthorityPath);
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText(TestCredentials.ServerCertChainPath),
                File.ReadAllText(TestCredentials.ServerPrivateKeyPath));

            var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, true);
            var clientCredentials = new SslCredentials(rootCert, keyCertPair);

            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client = TestService.NewClient(channel);
        }
Exemplo n.º 21
0
 public static void Main(string[] args)
 {
     // This code doesn't do much but makes sure the native extension is loaded
     // which is what we are testing here.
     Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure);
     c.ShutdownAsync().Wait();
     Console.WriteLine("Success!");
 }
Exemplo n.º 22
0
 public void Init()
 {
     server = new Server();
     server.AddServiceDefinition(ServiceDefinition);
     int port = server.AddPort(Host, Server.PickUnusedPort, ServerCredentials.Insecure);
     server.Start();
     channel = new Channel(Host, port, Credentials.Insecure);
 }
Exemplo n.º 23
0
 public void Init()
 {
     server = new Server();
     server.AddServiceDefinition(ServiceDefinition);
     int port = server.AddListeningPort(Host, Server.PickUnusedPort);
     server.Start();
     channel = new Channel(Host, port);
 }
Exemplo n.º 24
0
        public async UniTask DisposeAsync()
        {
            await _client.DisposeAsync();

            await _channel.ShutdownAsync();

            _channel = null;
        }
Exemplo n.º 25
0
        public NLClient(string jsonPath)
        {
            var credential = GoogleCredential.FromFile(jsonPath).CreateScoped(LanguageServiceClient.DefaultScopes);
            var channel    = new Grpc.Core.Channel(
                LanguageServiceClient.DefaultEndpoint.ToString(),
                credential.ToChannelCredentials());

            client = LanguageServiceClient.Create(channel);
        }
Exemplo n.º 26
0
 static void Main(string[] args)
 {
     var channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure);
     var client = new gRPC.gRPCClient(channel);
     var replay = client.SayHello(new HelloRequest { Name = "shoy" });
     Console.WriteLine(replay.Message);
     channel.ShutdownAsync().Wait();
     Console.ReadKey();
 }
Exemplo n.º 27
0
        // Creates a client to Juzusvr with mutually authenticated TLS.
        // The PEM encoded root certificates, PEM encoded client certificate
        // and the client's PEM private key must be provided as strings.
        public Client(string url, string rootCert, string clientCert, string clientKey)
        {
            this.serverURL = url;
            var keyCertPair = new Grpc.Core.KeyCertificatePair(clientCert, clientKey);

            this.creds   = new Grpc.Core.SslCredentials(rootCert, keyCertPair);
            this.channel = new Grpc.Core.Channel(url, this.creds, this.defaultChannelOptions());
            this.client  = client = new CobaltSpeech.Juzu.Juzu.JuzuClient(channel);
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            var channel = new Grpc.Core.Channel("127.0.0.1", 8890, ChannelCredentials.Insecure);
            var client  = new Greeter.GreeterClient(channel);
            var res     = client.SayHello(new HelloRequest {
                Name = "123123"
            });

            Console.WriteLine("Hello World!");
        }
Exemplo n.º 29
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(ServiceDefinition);
            int port = server.AddPort(Host, Server.PickUnusedPort, ServerCredentials.Insecure);
            server.Start();
            channel = new Channel(Host, port, Credentials.Insecure);

            stringFromServerHandlerTcs = new TaskCompletionSource<string>();
        }
Exemplo n.º 30
0
        public DefaultRpcChannel(IRpcServiceDiscovery rpcServiceDiscovery, ISerializer serializer, IOptions <RpcClientOptions> options)
        {
            var(host, port) = rpcServiceDiscovery == null
                ? (options.Value.Host, options.Value.Port)
                : rpcServiceDiscovery.ResolveAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            var channel = new GrpcCore.Channel(host, port, GrpcCore.ChannelCredentials.Insecure);

            this._invoker    = new GrpcCore.DefaultCallInvoker(channel);
            this._serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
        }
Exemplo n.º 31
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public HubConnector(TClient receiver, string ipAddr, int port)
        {
            ClientImpl = receiver;

            channel = new Grpc.Core.Channel(ipAddr, port, ChannelCredentials.Insecure);
            channel.ShutdownToken.Register(() =>
            {
                Debug.Log("Call ShutdownToken From Register");
            });
        }
        public void Init()
        {
            helper = new MockServiceHelper();

            server = helper.GetServer();
            server.Start();
            channel = helper.GetChannel();

            headers = new Metadata { { "ascii-header", "abcdefg" } };
        }
Exemplo n.º 33
0
        /// <summary>同步集群中MasterLeader
        /// </summary>
        private async void GrpcSyncMasterLeader()
        {
            if (_masterLeaderChannel == null)
            {
                _logger.LogError("同步MasterLeader出错,当前MasterLeaderChannel为空.");
                return;
            }

            try
            {
                var client  = GetMasterClient();
                var request = new MasterPb.KeepConnectedRequest()
                {
                    Name = Guid.NewGuid().ToString("N")
                };

                using (var call = client.KeepConnected())
                {
                    var responseReaderTask = Task.Run(() =>
                    {
                        while (call.ResponseStream.MoveNext(CancellationToken.None).WaitResult(5000))
                        {
                            var volumeLocation = call.ResponseStream.Current;

                            //接收到VolumeLocation信息后处理...
                            if (!volumeLocation.Leader.IsNullOrWhiteSpace() && !volumeLocation.Leader.Equals(_masterLeaderChannel.Target, StringComparison.OrdinalIgnoreCase))
                            {
                                //不相等,创建新的连接
                                lock (SyncObject)
                                {
                                    var connectionAddress = new ConnectionAddress(volumeLocation.Leader);
                                    _masterLeaderChannel  = CreateChannel(connectionAddress);
                                }
                            }
                        }
                    });
                    await call.RequestStream.WriteAsync(request);

                    await call.RequestStream.CompleteAsync();

                    await responseReaderTask;
                }
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    _logger.LogError(e.InnerException, "同步MasterLeader出现线程异常,{0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "同步MasterLeader出错,{0}", ex.Message);
            }
        }
 public void Init()
 {
     server = new Server
     {
         Services = { TestService.BindService(new UnimplementedTestServiceImpl()) },
         Ports = { { Host, ServerPort.PickUnused, SslServerCredentials.Insecure } }
     };
     server.Start();
     channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);
     client = new TestService.TestServiceClient(channel);
 }
Exemplo n.º 35
0
 public void Init()
 {
     server = new Server
     {
         Services = { Math.BindService(new MathServiceImpl()) },
         Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
     };
     server.Start();
     channel = new Channel(Host, server.Ports.Single().BoundPort, Credentials.Insecure);
     client = Math.NewClient(channel);
 }
Exemplo n.º 36
0
    public void Run()
    {
        if (channel == null || client == null)
        {
            // 서버 연결
            string liveHost    = "183.99.10.187:20051";
            string inhouseHost = "127.0.0.1:20051";

            channel = new Grpc.Core.Channel(inhouseHost, Grpc.Core.ChannelCredentials.Insecure);
            client  = new RpcService.RpcServiceClient(channel);
        }
    }
Exemplo n.º 37
0
        public void Init()
        {
            serviceImpl = new HealthServiceImpl();

            server = new Server();
            server.AddServiceDefinition(Grpc.Health.V1Alpha.Health.BindService(serviceImpl));
            int port = server.AddListeningPort(Host, Server.PickUnusedPort);
            server.Start();
            channel = new Channel(Host, port);

            client = Grpc.Health.V1Alpha.Health.NewClient(channel);
        }
Exemplo n.º 38
0
        public ServerHost()
        {
            _server = new Server
            {
                Ports =
                {
                    new ServerPort("localhost", Port, ServerCredentials.Insecure)
                }
            };

            Channel = new GrpcChannel("localhost", Port, ChannelCredentials.Insecure);
        }
Exemplo n.º 39
0
        public void Init()
        {
            server = new Server
            {
                Services = { ServiceDefinition },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, Credentials.Insecure);

            stringFromServerHandlerTcs = new TaskCompletionSource<string>();
        }
Exemplo n.º 40
0
        static async Task RunAsync(string endpoint, string prefix, ChannelOption[] options)
        {
            var channel = new Grpc.Core.Channel(endpoint, ChannelCredentials.Insecure, options);
            var client  = new Greeter.GreeterClient(channel);
            var user    = "******";

            var reply = client.SayHello(new HelloRequest {
                Name = user
            });

            Console.WriteLine("Greeting: " + reply.Message);

            // duplex
            var requestHeaders = new Metadata
            {
                { "x-host-port", "10-0-0-10" },
            };

            using var streaming = client.StreamingBothWays(requestHeaders);
            var readTask = Task.Run(async() =>
            {
                while (await streaming.ResponseStream.MoveNext())
                {
                    var response = streaming.ResponseStream.Current;
                    Console.WriteLine($"{prefix} {response.Message}");
                }
            });

            var i = 0;

            while (i++ < 100)
            {
                try
                {
                    await streaming.RequestStream.WriteAsync(new HelloRequest
                    {
                        Name = $"{prefix} {i}",
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{prefix} error {channel.State} {ex.Message} {ex.StackTrace}");
                }
                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            await streaming.RequestStream.CompleteAsync();

            await readTask;

            channel.ShutdownAsync().Wait();
        }
Exemplo n.º 41
0
        /// <summary>运行
        /// </summary>
        public void Start()
        {
            if (_isRunning)
            {
                return;
            }
            _masterLeaderChannel = CreateMasterChannel();
            //开启同步
            StartGrpcSyncMasterLeaderTask();

            //var channel=new GoogleGrpc.Channel("127.0.0.1")

            _isRunning = true;
        }
Exemplo n.º 42
0
        public void Init()
        {
            serviceImpl = new HealthServiceImpl();

            server = new Server
            {
                Services = { Grpc.Health.V1Alpha.Health.BindService(serviceImpl) },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = Grpc.Health.V1Alpha.Health.NewClient(channel);
        }
Exemplo n.º 43
0
        public async Task <string> ConnectToLnd(string host, string cert)
        {
            Debug.Log("connecting to lnd");

            HostName = host;
            Cert     = cert;
            var channelCreds = new SslCredentials(cert);

            rpcChannel = new Grpc.Core.Channel(host, channelCreds);

            lndClient = new Lightning.LightningClient(rpcChannel);
            InvokeRepeating("TryConnecting", 3, 5);
            return("connected");
        }
Exemplo n.º 44
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(TestService.BindService(new TestServiceImpl()));
            int port = server.AddPort(host, Server.PickUnusedPort, TestCredentials.CreateTestServerCredentials());
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            channel = new Channel(host, port, TestCredentials.CreateTestClientCredentials(true), options);
            client = TestService.NewClient(channel);
        }
Exemplo n.º 45
0
        public static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:50051", Credentials.Insecure);

            var client = Greeter.NewClient(channel);
            String user = "******";

            var reply = client.SayHello(new HelloRequest { Name = user });
            Console.WriteLine("Greeting: " + reply.Message);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 46
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            server = new Server
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
Exemplo n.º 47
0
    // Connect instantiates a new server connexion and instatiantes the main
    // character.
    public bool Connect(string endpoint)
    {
        if (endpoint == "")
        {
            endpoint = "[::1]:50051";
        }
        Debug.Log(endpoint);

        _grpc_channel = new Grpc.Core.Channel(
            endpoint, Grpc.Core.ChannelCredentials.Insecure);
        _client      = new Game.GameClient(_grpc_channel);
        is_connected = true;

        return(true);
    }
Exemplo n.º 48
0
        public static async Task MainAsync()
        {
            var channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

            var client = new Greeter.GreeterClient(channel);

            var user = Environment.UserName;

            var reply = client.SayHello(new HelloRequest { Name = user });
            Console.WriteLine("Greeting: {0}", reply.Message);

            await channel.ShutdownAsync().ConfigureAwait(false);

            Console.ReadLine();
        }
Exemplo n.º 49
0
        public static void Main(string[] args)
        {
            GrpcEnvironment.Initialize();

            using (Channel channel = new Channel("127.0.0.1:50051"))
            {
                var client = Greeter.NewStub(channel);
                String user = "******";

                var reply = client.SayHello(new HelloRequest.Builder { Name = user }.Build());
                Console.WriteLine("Greeting: " + reply.Message);
            }

            GrpcEnvironment.Shutdown();
        }
Exemplo n.º 50
0
        static async Task <string> Reverse()
        {
            Channel channel = new Channel("localhost", 11111, ChannelCredentials.Insecure);

            RevService.Generated.RevService.RevServiceClient client = new RevService.Generated.RevService.RevServiceClient(channel);


            var data = new RevService.Generated.Data()
            {
                UserId = "aaa", Permissions = "a,b,c"
            };
            var res = await client.ReverseAsync(data);

            return(res.Permissions);
        }
Exemplo n.º 51
0
        public async Task <string> ConnectToLndWithMacaroon(string host, string cert, string macaroon)
        {
            Debug.Log("connecting to lnd");
            HostName = host;
            Cert     = cert;
            var macaroonCallCredentials = new MacaroonCallCredentials(macaroon);
            var sslCreds     = new SslCredentials(cert);
            var channelCreds = ChannelCredentials.Create(sslCreds, macaroonCallCredentials.credentials);

            rpcChannel = new Grpc.Core.Channel(host, channelCreds);
            lndClient  = new Lightning.LightningClient(rpcChannel);
            InvokeRepeating("TryConnecting", 3, 5);

            return("connected");
        }
Exemplo n.º 52
0
    // proto: https://github.com/googleapis/googleapis/tree/master/google
    // c# code: https://github.com/googleapis/google-api-dotnet-client/tree/master/Src
    public static Grpc.Core.CallInvoker create(string url)
    {
        if (!initialized)
        {
            initialized = true;
            var path = System.Configuration.ConfigurationManager.AppSettings["google-cloud-service-account"];
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
        }
        var ev                = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
        var token             = Google.Apis.Auth.OAuth2.GoogleCredential.GetApplicationDefault();
        var channelCredential = Grpc.Auth.GoogleGrpcCredentials.ToChannelCredentials(token);
        var channel           = new Grpc.Core.Channel(url, channelCredential);

        return(new Grpc.Core.DefaultCallInvoker(channel));
    }
Exemplo n.º 53
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(Math.BindService(new MathServiceImpl()));
            int port = server.AddPort(host, Server.PickUnusedPort, ServerCredentials.Insecure);
            server.Start();
            channel = new Channel(host, port, Credentials.Insecure);
            client = Math.NewClient(channel);

            // TODO(jtattermusch): get rid of the custom header here once we have dedicated tests
            // for header support.
            client.HeaderInterceptor = (metadata) =>
            {
                metadata.Add(new Metadata.Entry("customHeader", "abcdef"));
            };
        }
Exemplo n.º 54
0
        public async Task <IActionResult> OnGetImageAsync(int postId)
        {
            //var channel = GrpcChannel.ForAddress("http://localhost:5005");
            //var client = new Servers.Vega.FileService.FileServiceClient(channel);

            var channel = new Grpc.Core.Channel("localhost:5005", SslCredentials.Insecure);
            var client  = new Servers.Vega.FileService.FileServiceClient(channel);

            var result = await client.DownloadFileAsync(new Servers.Vega.DownloadRequest
            {
                PostId = postId
            });


            return(File(result.Content.ToArray(), result.ContentType));
        }
Exemplo n.º 55
0
        public async Task <IActionResult> OnPostAsync(int postId)
        {
            var likeChannel = new Grpc.Core.Channel("localhost:5007", SslCredentials.Insecure);
            var likeClient  = new Liker.LikerClient(likeChannel);

            var reply = await likeClient.AddImageLikeAsync(new PostIdRequest()
            {
                PostId = postId,
                UserId = User.GetUserId(),
                //Status = PostIdRequest.Types.Status.Like
            });

            IsLiked = true;

            return(new RedirectToPageResult("", new{ postId = postId }));
        }
Exemplo n.º 56
0
 private void Form1_Load(object sender, EventArgs e)
 {
     try
     {
         //Create a connection
         var channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
         var rClient = new RobotService.RobotServiceClient(channel);
         var client = new RobotServiceClient(rClient);
         Console.WriteLine("Loaded");
         client.StreamReport();
     }
     catch (Exception err)
     {
         MessageBox.Show("Failed to load:", err.Message);
     }
 }
        public async Task <KestrelHost> StartAsync()
        {
            GrpcChannelExtensions.Http2UnencryptedSupport = true;

            _host = Host
                    .CreateDefaultBuilder()
                    .ConfigureServices(services =>
            {
                services.AddGrpc();
                services.AddServiceModelGrpc();
                _configureServices?.Invoke(services);
            })
                    .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.Configure(app =>
                {
                    app.UseRouting();

                    _configureApp?.Invoke(app);

                    if (_configureEndpoints != null)
                    {
                        app.UseEndpoints(_configureEndpoints);
                    }
                });

                webBuilder.UseKestrel(o => o.ListenLocalhost(_port, l => l.Protocols = HttpProtocols.Http2));
            })
                    .Build();

            try
            {
                await _host.StartAsync();
            }
            catch
            {
                await DisposeAsync();

                throw;
            }

            ClientFactory = new ClientFactory(_clientFactoryDefaultOptions);
            Channel       = new GrpcChannel("localhost", DefaultPort, ChannelCredentials.Insecure);

            return(this);
        }
Exemplo n.º 58
0
        public void Init()
        {
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;
            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client = TestService.NewClient(channel);
        }
Exemplo n.º 59
0
        public static void Main(string[] args)
        {
            var channel = new Channel("127.0.0.1", 23456, ChannelCredentials.Insecure);
            Math.IMathClient client = new Math.MathClient(channel);
            MathExamples.DivExample(client);

            MathExamples.DivAsyncExample(client).Wait();

            MathExamples.FibExample(client).Wait();

            MathExamples.SumExample(client).Wait();

            MathExamples.DivManyExample(client).Wait();

            MathExamples.DependendRequestsExample(client).Wait();

            channel.ShutdownAsync().Wait();
        }
        /**
         * Get the last block received by this peer.
         *
         * @return The last block received by this peer. May return null if no block has been received since first reactivated.
         */


        private Task ConnectEnvelopeAsync(Envelope envelope, CancellationToken token)
        {
            if (shutdown)
            {
                logger.Warn($"{ToString()} not connecting is shutdown.");
                return(Task.FromResult(0));
            }

            Channel lmanagedChannel = managedChannel;

            if (lmanagedChannel == null || lmanagedChannel.State == ChannelState.Shutdown || lmanagedChannel.State == ChannelState.TransientFailure)
            {
                lmanagedChannel = channelBuilder.BuildChannel();
                managedChannel  = lmanagedChannel;
            }

            return(DeliverAsync(lmanagedChannel, envelope, token));
        }