Exemple #1
0
        static void Main(string[] args)
        {
            Channel channel = new Channel();
            HelloService service = new HelloService();
            channel.AddMethod<HelloRequest, HelloSerializer>("maid.example.HelloService.HelloNotify", service.HelloNotify);
            channel.AddMethod<HelloRequest, HelloSerializer, HelloResponse, HelloSerializer>("maid.example.HelloService.HelloRpc", service.HelloRpc);
            channel.ConnectedCallback.Add(() =>
            {
                Console.WriteLine("连接上了");
            });

            channel.Connect("192.168.0.99", 8888);

            while (true)
            {
                channel.Update();

                HelloRequest request = new HelloRequest();
                request.message = "this message from protobuf-net";
                try
                {
                    channel.CallMethod("maid.example.HelloService.HelloNotify", request);
                    channel.CallMethod("maid.example.HelloService.HelloRpc", request);
                }
                catch (Exception ){ }
                if (channel.Connecting)
                {
                    Console.WriteLine("连接中");
                }
            }
        }
Exemple #2
0
 public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     Console.WriteLine($"{context.Method}:{context.Peer} time:{Utils.GetTimeNow()}");
     foreach (var header in context.RequestHeaders)
     {
         Console.WriteLine($"{header.Key}:{header.Value}");
     }
     return Task.FromResult(new HelloReply { Message = "holle " + request.Name });
 }
Exemple #3
0
 private HelloResponse Hello(HelloRequest request)
 {
     return(Ok(new HelloResponse()));
 }
 public override Task <HelloResponse> greeting(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloResponse {
         Greeting = "Hello " + request.Name
     }));
 }
Exemple #5
0
 public override Task SayHellos(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
 {
     return(base.SayHellos(request, responseStream, context));
 }
Exemple #6
0
 // Server side handler of the SayHello RPC
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(this.greeterCore.SayHello <HelloReply>(request)));
 }
        static void Main(string[] args)
        {
            args    = new[] { "" };
            args[0] = "listen";

            switch (args[0].ToLower())
            {
            case "listen":
            {
                ////using (RpcServer.CreateRpc(IID, new Impersonation(new MyService.ServerStub(new Implementation())))
                //using (RpcServer.CreateRpc(IID, new Impersonation(new Greeter.ServerStub(new Implementation_Greeter())))
                //    //.AddAuthentication(CSharpTest.Net.RpcLibrary.RpcAuthentication.RPC_C_AUTHN_NONE)
                //    //.AddAuthNegotiate()
                //    .AddProtocol("ncacn_ip_tcp", "50051")
                //    //.AddProtocol("ncacn_np", @"\pipe\Greeter")
                //    ////.AddProtocol("ncalrpc", "MyService")
                //    //.AddProtocol("ncalrpc", "Greeter")
                //    .StartListening())
                //{
                //    Console.WriteLine("Waiting for connections...");
                //    Console.ReadLine();
                //}


                Guid iid = Marshal.GenerateGuidForType(typeof(IGreeter));
                using (RpcServer.CreateRpc(iid, new Greeter.ServerStub(new Anonymous_Greeter()))
                       //.AddAuthNegotiate()
                       .AddAuthentication(CSharpTest.Net.RpcLibrary.RpcAuthentication.RPC_C_AUTHN_NONE)
                       .AddAuthNegotiate()
                       .AddProtocol("ncacn_ip_tcp", "50051")
                       //.AddProtocol("ncalrpc", "Greeter")
                       .StartListening())
                {
                    Console.WriteLine("Waiting for connections...");
                    string name = "123";         // Console.ReadLine();


                    using (Greeter client = new Greeter(RpcClient
                                                        .ConnectRpc(iid, "ncacn_ip_tcp", @"localhost", "50051")
                                                        .Authenticate(RpcAuthenticationType.Self)
                                                        //.Authenticate(RpcAuthenticationType.None)
                                                        ))
                    {
                        HelloReply response = client.SayHello(HelloRequest.CreateBuilder().SetName(name).Build());
                        Console.WriteLine("OK: " + response.Message);
                    }
                    Console.ReadLine();
                }

                //Guid iid = Marshal.GenerateGuidForType(typeof(IBookService));
                //using (RpcServer.CreateRpc(iid, new BookService.ServerStub(new Anonymous_BookService()))
                //    .AddProtocol("ncacn_ip_tcp", "50051")
                //    .AddProtocol("ncalrpc", "BookService")
                //    .StartListening())
                //{
                //    Console.WriteLine("Waiting for connections...");
                //    Console.ReadLine();
                //}


                break;
            }

            case "send-lrpc":
            {
                using (MyService client = new MyService(
                           RpcClient.ConnectRpc(IID, "ncalrpc", null, "MyService")
                           .Authenticate(RpcAuthenticationType.Self)))
                {
                    MyResponse response = client.Send(
                        MyRequest.CreateBuilder().SetMessage("Hello via LRPC!").Build());
                }
                break;
            }

            case "send-tcp":
            {
                using (MyService client = new MyService(
                           RpcClient.ConnectRpc(IID, "ncacn_ip_tcp", @"localhost", "8080")
                           .Authenticate(RpcAuthenticationType.Self)))
                {
                    MyResponse response = client.Send(
                        MyRequest.CreateBuilder().SetMessage("Hello via Tcp/Ip!").Build());
                }
                break;
            }

            case "send-np":
            {
                using (MyService client = new MyService(
                           RpcClient.ConnectRpc(IID, "ncacn_np", @"\\localhost", @"\pipe\MyService")
                           .Authenticate(RpcAuthenticationType.Self)))
                {
                    MyResponse response = client.Send(
                        MyRequest.CreateBuilder().SetMessage("Hello via Named Pipe!").Build());
                }
                break;
            }

            case "send-anon":
            {
                using (MyService client = new MyService(
                           RpcClient.ConnectRpc(IID, "ncacn_np", @"\\localhost", @"\pipe\MyService")
                           .Authenticate(RpcAuthenticationType.Anonymous)))
                {
                    try
                    {
                        MyResponse response = client.Send(
                            MyRequest.CreateBuilder().SetMessage("Hello from Anonymous!").Build());
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                }
                break;
            }
            }
        }
Exemple #8
0
 private HelloResponse ProcessHelloRequest(HelloRequest request)
 {
     IList<RemoteConnectorInfoImpl> connectorInfo = null;
     IList<ConnectorKey> connectorKeys = null;
     IDictionary<string, object> serverInfo = null;
     Exception exception = null;
     try
     {
         serverInfo = new Dictionary<string, object>(1);
         if (request.isServerInfo())
         {
             serverInfo.Add(HelloResponse.SERVER_START_TIME, _server.StartTime());
         }
         if (request.isConnectorKeys())
         {
             ConnectorInfoManager manager = GetConnectorInfoManager();
             IList<ConnectorInfo> localInfos = manager.ConnectorInfos;
             connectorKeys = new List<ConnectorKey>();
             foreach (ConnectorInfo localInfo in localInfos)
             {
                 connectorKeys.Add(localInfo.ConnectorKey);
             }
             if (request.isConnectorInfo())
             {
                 connectorInfo = new List<RemoteConnectorInfoImpl>();
                 foreach (ConnectorInfo localInfo in localInfos)
                 {
                     LocalConnectorInfoImpl localInfoImpl =
                             (LocalConnectorInfoImpl)localInfo;
                     RemoteConnectorInfoImpl remoteInfo =
                             localInfoImpl.ToRemote();
                     connectorInfo.Add(remoteInfo);
                 }
             }
         }
     }
     catch (Exception e)
     {
         TraceUtil.TraceException(null, e);
         exception = e;
         connectorInfo = null;
     }
     return new HelloResponse(exception, serverInfo, connectorKeys, connectorInfo);
 }
Exemple #9
0
 protected virtual void OnHelloRequest(HelloRequest helloRequest)
 {
     HelloRequest?.Invoke(this, new HelloRequestEventArgs(helloRequest));
 }
 public HelloResponse SayHello(HelloRequest request)
 {
     return(new HelloResponse {
         Result = "Hello " + request.Name, CorrelationIdentifier = request.CorrelationIdentifier
     });
 }
Exemple #11
0
 // Server side handler of the SayHello RPC
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloReply {
         Message = GetAnswer(request)
     }));
 }
Exemple #12
0
 public string GetAnswer(HelloRequest request)
 {
     // throw new Exception("Argh exception!!");
     return($"Hello to {request.Name}");
 }
Exemple #13
0
 void Handle(HelloRequest helloRequest)
 {
     Console.WriteLine($"处理:HelloRequest: Message={helloRequest.Message},Amount={helloRequest.Amount}");
 }
Exemple #14
0
 public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
     => Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
Exemple #15
0
 // Server side handler of the SayHello RPC
 public Task<HelloReply> SayHello(ServerCallContext context, HelloRequest request)
 {
     var reply = new HelloReply.Builder { Message = "Hello " + request.Name }.Build();
     return Task.FromResult(reply);
 }
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloReply {
         Message = "Hello " + request.Name
     }));
 }
Exemple #17
0
 /// <inheritdoc />
 public override Task <HelloResponse> Hello(HelloRequest request, ServerCallContext context) => _contentServer.HelloAsync(request, context.CancellationToken);
Exemple #18
0
        protected virtual void HandleRequests(MessageHeader rp, MemoryStream ms)
        {
            switch (rp.Operation)
            {
            case NetOperationType.Blocks:
                BlockRequest blockRequest  = new BlockRequest(ms, rp);
                var          blockResponse = new BlockResponse
                {
                    RequestId = blockRequest.RequestId,
                    Blocks    = BlockChain.Instance.GetBlocks(blockRequest.StartBlock, blockRequest.EndBlock)
                };
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    blockResponse.SaveToStream(memoryStream);
                    memoryStream.Position = 0;
                    SendRaw(memoryStream);
                }

                break;

            case NetOperationType.Transactions:
            {
                BlockRequest  transactionBlockRequest  = new BlockRequest(ms, rp);
                BlockResponse transactionBlockResponse = new BlockResponse
                {
                    RequestId = transactionBlockRequest.RequestId,
                    Blocks    = BlockChain.Instance.GetBlocks(transactionBlockRequest.StartBlock,
                                                              transactionBlockRequest.EndBlock).ToList()
                };
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    transactionBlockResponse.SaveToStream(memoryStream);
                    memoryStream.Position = 0;
                    SendRaw(memoryStream);
                }
                break;
            }

            case NetOperationType.CheckPoint:
                break;

            case NetOperationType.Hello:
                HelloRequest request = new HelloRequest(ms, rp);
                Node.Instance.NodeServers.UpdateNodeServers(request.NodeServers);
                HelloResponse response = new HelloResponse(request)
                {
                    Timestamp   = DateTime.UtcNow,
                    Error       = 0,
                    ServerPort  = Node.NetParams.Port,
                    Block       = BlockChain.Instance.GetLastBlock(),
                    WorkSum     = CheckPoints.WorkSum,
                    AccountKey  = Node.Instance.NodeKey,
                    RequestType = RequestType.Response,
                    Operation   = NetOperationType.Hello
                };
                using (MemoryStream vm = new MemoryStream())
                {
                    response.SaveToStream(vm);
                    vm.Position = 0;
                    SendRaw(vm);
                }
                break;
            }
        }
Exemple #19
0
 public void HelloRpc(Controller controller, HelloRequest request, HelloResponse response)
 {
     Console.WriteLine("request: " + request.message + " response: " + response.message);
 }
Exemple #20
0
 public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     _logger.LogInformation($"Sending hello to {request.Name}");
     return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
 }
            static Task SayHellosBufferHint(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
            {
                context.WriteOptions = new WriteOptions(WriteFlags.BufferHint);

                return(GreeterService.SayHellosCore(request, responseStream));
            }
Exemple #22
0
 public global::System.Threading.Tasks.ValueTask <HelloReply> SayHelloAsync(HelloRequest value, global::ProtoBuf.Grpc.CallContext context = default)
 {
     throw new NotImplementedException();
 }
 public override Task <HelloReply> SayHelloAgain(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloReply {
         Message = $"Hello {request.Name} again..."
     }));
 }
 // Server side handler of the SayHello RPC
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloReply {
         Message = "Hello " + request.Name + " (Backend IP: " + Environment.GetEnvironmentVariable("MY_POD_IP") + ")"
     }));
 }
        public override async Task SayHellosSendHeadersFirst(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
        {
            await context.WriteResponseHeadersAsync(null);

            await SayHellosCore(request, responseStream);
        }
Exemple #26
0
 public HelloRequestEventArgs(HelloRequest helloRequest)
 {
     HelloRequest = helloRequest;
 }
        public override Task <HelloReply> SayHelloThrow(HelloRequest request, ServerCallContext context)
        {
            var user = context.GetHttpContext().User;

            throw new Exception($"user:{user} - oh my, Derek said it would work!");
        }
 public object Any(HelloRequest request)
 {
     return new HelloResponse { Result = "HelloRequest, " + request.Name };
 }
Exemple #29
0
 public Task <HelloReply> SayHello(HelloRequest request)
 {
     return(Task.FromResult(new HelloReply {
         Message = "Hello " + request.Name
     }));
 }
 public override Task <HelloReply> SayHello2(HelloRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloReply {
         Message = "1231231"
     }));
 }
        public async Task UnaryMethodDeadlineExceeded(bool throwErrorOnCancellation)
        {
            async Task <HelloReply> WaitUntilDeadline(HelloRequest request, ServerCallContext context)
            {
                try
                {
                    await Task.Delay(1000, context.CancellationToken);
                }
                catch (OperationCanceledException) when(!throwErrorOnCancellation)
                {
                    // nom nom nom
                }

                return(new HelloReply());
            }

            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName)
                {
                    // Deadline happened before write
                    if (writeContext.EventId.Name == "ErrorExecutingServiceMethod" &&
                        writeContext.State.ToString() == "Error when executing service method 'WaitUntilDeadline-True'.")
                    {
                        return(true);
                    }
                }

                return(false);
            });

            var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(WaitUntilDeadline, $"{nameof(WaitUntilDeadline)}-{throwErrorOnCancellation}");

            var grpcWebClient = CreateGrpcWebClient();

            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create(method.FullName);

            httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "300m");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            try
            {
                // Act
                var response = await grpcWebClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();

                // Assert
                response.AssertIsSuccessfulGrpcRequest();
                response.AssertTrailerStatus(StatusCode.DeadlineExceeded, "Deadline Exceeded");
            }
            catch (Exception ex) when(Net.Client.Internal.GrpcProtocolHelpers.ResolveRpcExceptionStatusCode(ex) == StatusCode.Cancelled)
            {
                // Ignore exception from deadline abort
            }
        }
Exemple #32
0
 // Server side handler of the SayHello RPC
 public Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
 }
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     return(base.SayHello(request, context));
 }
 public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 => Task.FromResult(new HelloReply
 {
     Message = $"Hello {request.Name}"
 });
 /// <inheritdoc />
 protected override AsyncUnaryCall <HelloResponse> HelloAsync(HelloRequest helloRequest, CancellationToken token)
 {
     return(Client.HelloAsync(helloRequest, cancellationToken: token));
 }
Exemple #36
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine();
            Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

            var client = new Greeter.GreeterClient(channel);

            var request = new HelloRequest {
                Name = "Thomas"
            };

            #region Unary RPC
            Log("Unary RPC");

            var reply = client.SayHello(request);
            Log("Greeting: " + reply.Message);

            try
            {
                var secondReply = client.SayHello(request, deadline: DateTime.UtcNow.AddMilliseconds(2));
                Log("Greeting: " + secondReply.Message);
            }
            catch (RpcException e)
            {
                Log(e.Status.Detail);
            }

            Console.WriteLine();
            #endregion

            #region Server streaming RPC
            Log("Server streaming RPC");

            using (var call = client.LotsOfReplies(request))
            {
                while (await call.ResponseStream.MoveNext())
                {
                    var streamReply = call.ResponseStream.Current;
                    Log(streamReply.ToString());
                }
            }

            Console.WriteLine();
            #endregion

            #region Client streaming RPC
            Log("Client streaming RPC");

            using (var call = client.GreetingsLog())
            {
                var names = new[] { "Thomas", "Max", "Ben" };
                foreach (var name in names)
                {
                    await call.RequestStream.WriteAsync(new HelloRequest { Name = name });
                }
                await call.RequestStream.CompleteAsync();

                var greetingsReply = await call.ResponseAsync;
                Log(greetingsReply.Message);
            }

            Console.WriteLine();
            #endregion

            #region Bidirectional RPC
            Log("Bidirectional RPC");

            using (var call = client.GreetingsPong())
            {
                var readerTask = Task.Run(async() =>
                {
                    while (await call.ResponseStream.MoveNext())
                    {
                        var msg = call.ResponseStream.Current.Message;
                        Log(msg);
                    }
                });
                var names = new[] { "Thomas", "Max", "Ben" };
                foreach (var name in names)
                {
                    await call.RequestStream.WriteAsync(new HelloRequest { Name = name });
                }
                await call.RequestStream.CompleteAsync();

                await readerTask;
            }

            Console.WriteLine();
            #endregion

            await channel.ShutdownAsync();

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
Exemple #37
0
 public void HelloNotify(Controller controller, HelloRequest request)
 {
     Console.WriteLine("notify: " + request.message);
 }
Exemple #38
0
 protected void OnRequestReceived(HelloRequest request)
 {
     this.RequestReceived?.Invoke(this, new MessageReceivedEventArgs <HelloRequest>(request, this.DialogProvider));
 }
Exemple #39
0
 protected abstract AsyncUnaryCall <HelloResponse> HelloAsync(HelloRequest helloRequest, CancellationToken token);
Exemple #40
0
 private HelloResponse ProcessHelloRequest(HelloRequest request)
 {
     IList<RemoteConnectorInfoImpl> connectorInfo;
     Exception exception = null;
     try
     {
         ConnectorInfoManager manager =
             GetConnectorInfoManager();
         IList<ConnectorInfo> localInfos =
             manager.ConnectorInfos;
         connectorInfo = new List<RemoteConnectorInfoImpl>();
         foreach (ConnectorInfo localInfo in localInfos)
         {
             LocalConnectorInfoImpl localInfoImpl =
                 (LocalConnectorInfoImpl)localInfo;
             RemoteConnectorInfoImpl remoteInfo =
                 localInfoImpl.ToRemote();
             connectorInfo.Add(remoteInfo);
         }
     }
     catch (Exception e)
     {
         TraceUtil.TraceException(null, e);
         exception = e;
         connectorInfo = null;
     }
     return new HelloResponse(exception, connectorInfo);
 }