public ClientSessionContext( ITransportReceiveHandler transportReceiveHandler, RpcClientOptions options, RpcSocketAsyncEventArgs socketContext ) { if ( transportReceiveHandler == null ) { throw new ArgumentNullException( "transportReceiveHandler" ); } if ( options == null ) { throw new ArgumentNullException( "options" ); } if ( socketContext == null ) { throw new ArgumentNullException( "socketContext" ); } Contract.EndContractBlock(); this._transportReceiveHandler = transportReceiveHandler; this._options = options; this._socketContext = socketContext; }
public static RpcClientOptions AddConsoleLogger(this RpcClientOptions options) { options.Extensions.Add(new RpcClientExtension { PreSendRequestAction = y => { Console.WriteLine($"Request: {y.Id}"); Console.WriteLine($"POST {y.BaseAddress}/{y.MethodName}"); var json = y.Arguments != null ? JsonConvert.SerializeObject(y.Arguments) : null; if (json != null) { Console.WriteLine($"Args: {json}"); } }, PostReceiveResponseAction = y => { Console.WriteLine($"Response: {y.Id}"); Console.WriteLine($"POST {y.BaseAddress}/{y.MethodName}"); var json = y.Arguments != null ? JsonConvert.SerializeObject(y.Arguments) : null; if (json != null) { Console.WriteLine($"Args: {json}"); } var j2 = y.Result != null ? JsonConvert.SerializeObject(y.Result) : null; if (j2 != null) { Console.WriteLine($"Result: {j2}"); } } }); return(options); }
private static void AssertOptions(RpcClientOptions options, ImmutableRpcClientOptions actualOptions) { Assert.AreEqual(options.CallTimeout, actualOptions.CallTimeout); Assert.AreEqual(options.ReceiveMaxMessageSize, actualOptions.ReceiveMaxMessageSize); Assert.AreEqual(options.SendMaxMessageSize, actualOptions.SendMaxMessageSize); Assert.AreEqual(options.StreamingCallTimeout, actualOptions.StreamingCallTimeout); Assert.AreEqual(options.Serializer, actualOptions.Serializer); }
public GrpcFullStackTests(IRpcSerializer serializer) { this.options = new RpcServerOptions { Serializer = serializer }; this.clientOptions = new RpcClientOptions { Serializer = serializer }; }
public TcpClientTransport( EndPoint remoteEndPoint, RpcTransportProtocol protocol, ClientEventLoop eventLoop, RpcClientOptions options ) : base(remoteEndPoint, protocol, eventLoop, options) { if ( protocol.ProtocolType != ProtocolType.Tcp ) { throw new ArgumentException( "socket must be connected TCP socket.", "protocol" ); } Contract.EndContractBlock(); }
public override ResponseMessageSerializer Create( RpcTransportProtocol protocol, RpcClientOptions options ) { return new ResponseMessageSerializer( null, null, null, null, options == null ? _defaultResponseQuota : options.MaximumRequestQuota ?? _defaultResponseQuota ); }
public PollingClientEventLoop( Func<ClientSessionContext, RpcClient> sessionFactory, RpcClientOptions options, EventHandler<RpcTransportErrorEventArgs> errorHandler ) : base(sessionFactory, options, errorHandler) { this._cancellationTokenSource = new CancellationTokenSource(); int connectingConcurrency = options == null ? Environment.ProcessorCount / 5 + 1 : ( options.ConnectingConcurrency ?? Environment.ProcessorCount / 5 + 1 ); int sendingConcurrency = options == null ? ( Environment.ProcessorCount / 5 + 1 ) * 2 : ( options.SendingConcurrency ?? ( Environment.ProcessorCount / 5 + 1 ) * 2 ); int receivingConcurrency = options == null ? ( Environment.ProcessorCount / 5 + 1 ) * 2 : ( options.ReceivingConcurrency ?? ( Environment.ProcessorCount / 5 + 1 ) * 2 ); this._connectingQueue = new NotifiableBlockingCollection<ClientSocketAsyncEventArgs>( new ConcurrentQueue<ClientSocketAsyncEventArgs>(), options == null ? connectingConcurrency * 4 : ( options.ConnectingQueueLength ?? connectingConcurrency * 4 ) ); this._sendingQueue = new NotifiableBlockingCollection<ClientSocketAsyncEventArgs>( new ConcurrentQueue<ClientSocketAsyncEventArgs>(), options == null ? sendingConcurrency * 4 : ( options.SendingQueueLength ?? sendingConcurrency * 4 ) ); for ( int i = 0; i < connectingConcurrency; i++ ) { this.BeginWaitForOnConnecting(); } for ( int i = 0; i < sendingConcurrency; i++ ) { this.BeginWaitForOnSending(); } this._inBoundPollingThread = new Thread( this.PollInBound ); this._inBoundPollingThread.IsBackground = true; this._inBoundPollingThread.Name = String.Format( CultureInfo.InvariantCulture, "{0}({1}).InBoundPollingThread", this.GetType().Name, this.GetHashCode() ); this._inBoundPollingThread.Start( this._cancellationTokenSource.Token ); }
protected ClientTransport( RpcTransportProtocol protocol, ClientEventLoop eventLoop, RpcClientOptions options ) { if ( eventLoop == null ) { throw new ArgumentNullException( "eventLoop" ); } Contract.EndContractBlock(); this._eventLoop = eventLoop; this._requestSerializer = ClientServices.RequestSerializerFactory.Create( protocol, options ); this._responseSerializer = ClientServices.ResponseDeserializerFactory.Create( protocol, options ); this._drainTimeout = options == null ? TimeSpan.FromSeconds( 3 ) : options.DrainTimeout ?? TimeSpan.FromSeconds( 3 ); this._options = options ?? new RpcClientOptions(); this._options.Freeze(); }
static async Task Main(string[] args) { var options = new RpcClientOptions { BaseAddress = "https://localhost:44318/", //Serializer = new ProtobufSerializer() } .AddConsoleLogger(); var client = RpcClient <IDemoService> .Create(options); //RpcClient.SetAuthorization(client, "Bearer", "xyz..."); Console.WriteLine("RPC Demo Client is waiting - Press any key to begin."); Console.ReadKey(); await client.DoNothing(); Console.WriteLine(client.GetAge("Rush", 37)); Console.WriteLine(client.GetPersonAge(new Person { Id = 1, FirstName = "Rush", LastName = "Frisby" }, 37)); var echo2 = client.Echo("hello world"); Console.WriteLine($"Echo: {echo2}"); var echo = await client.EchoAsync("test"); Console.WriteLine(echo); var now = client.GetDateTime(); Console.WriteLine($"Now: {now}"); //var userName = client.GetUserName(); //Console.WriteLine($"User Name: {userName}"); var person = client.EchoPerson(new Person { Id = 1, FirstName = "Rush", LastName = "Frisby" }); Console.WriteLine($"Person: Id={person.Id}, FName={person.FirstName}, LName={person.LastName}"); Console.WriteLine("Done. Press any key to exit."); Console.ReadKey(); }
protected ConnectionOrientedClientTransport( EndPoint remoteEndPoint, RpcTransportProtocol protocol, ClientEventLoop eventLoop, RpcClientOptions options ) : base(protocol, eventLoop, options) { if ( remoteEndPoint == null ) { throw new ArgumentNullException( "remoteEndPoint" ); } this._connectionPool = new ConnectionPool( remoteEndPoint, protocol, eventLoop, options == null ? _defaultMinimumConnectionCount : ( options.MinimumConnectionCount ?? _defaultMinimumConnectionCount ), options == null ? _defaultMaximumConnectionCount : ( options.MaximumConnectionCount ?? _defaultMaximumConnectionCount ) ); this._connectTimeout = options == null ? _defaultConnectTimeout : ( options.ConnectTimeout ?? _defaultConnectTimeout ); }
public UdpClientTransport( RpcSocket socket, EndPoint remoteEndPoint, ClientEventLoop eventLoop, RpcClientOptions options ) : base(socket == null ? RpcTransportProtocol.UdpIp : socket.Protocol, eventLoop, options) { if ( socket == null ) { throw new ArgumentNullException( "socket" ); } if ( socket.Protocol.ProtocolType != ProtocolType.Udp ) { throw new ArgumentException( "socket must be connected TCP socket.", "socket" ); } if ( remoteEndPoint == null ) { throw new ArgumentNullException( "remoteEndPoint" ); } Contract.EndContractBlock(); this._socket = socket; this._remoteEndPoint = remoteEndPoint; }
/// <summary> /// Create <see cref="RequestMessageSerializer"/> for specified protocol and configuration. /// </summary> /// <param name="protocol">Target protocol.</param> /// <param name="options">Option settings. This parameter can be null.</param> /// <returns><see cref="RequestMessageSerializer"/> for specified protocol and configuration.</returns> public abstract ResponseMessageSerializer Create( RpcTransportProtocol protocol, RpcClientOptions options );
/// <summary> /// Create <see cref="ClientEventLoop"/> with specified options. /// </summary> /// <param name="options">Client side RPC options. This value may be null.</param> /// <param name="errorHandler">Aggreated error handler which will be associated to creating event loop. This value may be null.</param> /// <param name="cancellationTokenSource"><see cref="CancellationTokenSource"/> to cancel asynchronous operation. This value may be null.</param> /// <returns><see cref="ClientEventLoop"/>, which is specific to concrete factory class.</returns> protected abstract ClientEventLoop CreateCore( RpcClientOptions options, EventHandler<RpcTransportErrorEventArgs> errorHandler, CancellationTokenSource cancellationTokenSource );
private static async Task Main(string[] args) { var sslOptions = TestCertificates.SslClientOptions; string?token = null; var options = new RpcClientOptions(); options.Interceptors.Add(metadata => { if (token != null) { metadata.AddHeader("Authorization", $"Bearer {token}"); } return(Task.CompletedTask); }); var connection = new NetGrpcConnection(Address, options); var client = connection.GetServiceSingleton <ITicketerServiceClient>(); Console.WriteLine("gRPC Ticketer"); Console.WriteLine(); Console.WriteLine("Press a key:"); Console.WriteLine("1: Get available tickets"); Console.WriteLine("2: Purchase ticket (requires authorization)"); Console.WriteLine("3: Track ticket purchases (requires authentication)"); Console.WriteLine("4: Stop tracking ticket purchases (requires authentication)"); Console.WriteLine("5: Authenticate"); Console.WriteLine("6: Exit"); Console.WriteLine(); EventHandler <TicketPurchaseEventArgs> purchasedHandler = (s, e) => Console.WriteLine($"User '{e.User}' purchased '{e.TicketCount}' ticket(s)."); var exiting = false; while (!exiting) { var consoleKeyInfo = Console.ReadKey(intercept: true); switch (consoleKeyInfo.KeyChar) { case '1': await GetAvailableTickets(client); break; case '2': await PurchaseTicket(client, token); break; case '3': try { Console.WriteLine("Starting ticket purchase tracking..."); client.TicketsPurchased += purchasedHandler; await client.WaitForPendingEventHandlersAsync(); Console.WriteLine("Successfully started ticket purchase tracking."); } catch (Exception x) { Console.WriteLine("Error tracking ticket purchases." + Environment.NewLine + x.ToString()); } break; case '4': try { Console.WriteLine("Stopping ticket purchase tracking..."); client.TicketsPurchased -= purchasedHandler; await client.WaitForPendingEventHandlersAsync(); Console.WriteLine("Successfully stopped ticket purchase tracking."); } catch (Exception x) { Console.WriteLine("Error stopping ticket purchases tracking." + Environment.NewLine + x.ToString()); } break; case '5': token = await Authenticate(); break; case '6': exiting = true; break; } } Console.WriteLine("Exiting"); }
/// <summary> /// TODO: Use factories instead of using this.connnectionType. /// </summary> /// <param name="serviceDefinitionsProvider"></param> /// <param name="proxyDefinitionsProvider"></param> /// <returns></returns> protected (IRpcServerHost, IRpcChannel) CreateServerAndConnection( IRpcServiceDefinitionsProvider serviceDefinitionsProvider = null, Action <RpcServerOptions> configServerOptions = null, Action <RpcClientOptions> configClientOptions = null, Action <IServiceCollection> configureServices = null) { var rpcServerId = RpcServerId.NewId(); var serverOptions = new RpcServerOptions { Serializer = this.serializer }; var clientOptions = new RpcClientOptions { Serializer = this.serializer }; configServerOptions?.Invoke(serverOptions); configClientOptions?.Invoke(clientOptions); IServiceProvider services = GetServiceProvider(configureServices); switch (this.ConnectionType) { case RpcConnectionType.LightweightTcp: case RpcConnectionType.LightweightSslTcp: { var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions, loggerFactory: services.GetService <ILoggerFactory>()); SslServerOptions sslServerOptions = null; if (this.ConnectionType == RpcConnectionType.LightweightSslTcp) { sslServerOptions = new SslServerOptions(new X509Certificate2(TestCertificates.ServerPFXPath, "1111")); } host.AddEndPoint(new TcpRpcEndPoint("127.0.0.1", TcpTestPort, false, sslServerOptions)); SslClientOptions sslClientOptions = null; if (this.ConnectionType == RpcConnectionType.LightweightSslTcp) { sslClientOptions = new SslClientOptions { RemoteCertificateValidationCallback = this.ValidateTestCertificate }; } var connection = new TcpRpcConnection( new RpcConnectionInfo("TCP", new Uri($"lightweight.tcp://127.0.0.1:{TcpTestPort}"), rpcServerId), sslClientOptions, clientOptions.AsImmutable(), this.LightweightOptions); return(host, connection); } case RpcConnectionType.LightweightNamedPipe: { var server = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions, loggerFactory: services.GetService <ILoggerFactory>()); server.AddEndPoint(new NamedPipeRpcEndPoint("testpipe")); var connection = new NamedPipeRpcConnection( new RpcConnectionInfo(new Uri("lightweight.pipe://./testpipe")), clientOptions.AsImmutable(), this.LightweightOptions); return(server, connection); } case RpcConnectionType.LightweightInproc: { Pipe requestPipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool)); Pipe responsePipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.Inline)); var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, loggerFactory: services.GetService <ILoggerFactory>()); host.AddEndPoint(new InprocRpcEndPoint(new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer))); var connection = new InprocRpcConnection(new RpcConnectionInfo("Direct", new Uri("direct:localhost"), rpcServerId), new DirectDuplexPipe(responsePipe.Reader, requestPipe.Writer), clientOptions.AsImmutable()); return(host, connection); } case RpcConnectionType.Grpc: { var host = new GrpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions); host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint()); var connection = new GrpcConnection( new RpcConnectionInfo("TCP", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId), TestCertificates.GrpcSslCredentials, clientOptions.AsImmutable()); return(host, connection); } #if PLAT_NET_GRPC case RpcConnectionType.NetGrpc: { var server = CreateNetGrpcServer(serviceDefinitionsProvider, rpcServerId, serverOptions, configureServices); //var host = new GrpcServer(rpcServerId, serviceDefinitionsBuilder, null, options); //host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint()); var handler = new System.Net.Http.HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return(true); }; var channelOptions = new GrpcNet.Client.GrpcChannelOptions() { HttpClient = new System.Net.Http.HttpClient(handler), DisposeHttpClient = true }; var connection = new NetGrpcConnection( new RpcConnectionInfo("net-grpc", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId), clientOptions.AsImmutable(), channelOptions); return(server, connection); } #endif } throw new NotSupportedException(); }
/// <summary> /// Create <see cref="ClientEventLoop"/> with specified options. /// </summary> /// <param name="options">Client side RPC options. This value can be null.</param> /// <param name="errorHandler">Aggreated error handler which will be associated to creating event loop. This value can be null.</param> /// <param name="cancellationTokenSource"><see cref="CancellationTokenSource"/> to cancel asynchronous operation. This value can be null.</param> /// <returns><see cref="ClientEventLoop"/>, which is specific to concrete factory class.</returns> public ClientEventLoop Create( RpcClientOptions options, EventHandler<RpcTransportErrorEventArgs> errorHandler, CancellationTokenSource cancellationTokenSource ) { return this.CreateCore( options, errorHandler, cancellationTokenSource ); }
protected override sealed ClientEventLoop CreateCore( RpcClientOptions options, EventHandler<RpcTransportErrorEventArgs> errorHandler, CancellationTokenSource cancellationTokenSource ) { return new IOCompletionPortClientEventLoop( options, errorHandler, cancellationTokenSource ); }
public IOCompletionPortClientEventLoop( RpcClientOptions options, EventHandler<RpcTransportErrorEventArgs> errorHandler, CancellationTokenSource cancellationTokenSource ) : base(options, errorHandler, cancellationTokenSource) { }
public void TestTcpSend() { using ( var server = ServerMock.CreateTcp( 57129, 8192 ) ) using ( var serverDone = new ManualResetEventSlim() ) { Exception exceptionOnServer = null; int? requestId = null; server.Received += ( sender, e ) => { try { var request = e.GetRequest(); requestId = request.MessageId; Assert.AreEqual( MessageType.Request, request.MessageType ); Assert.AreEqual( "Test", request.Method ); Assert.AreEqual( 3, request.Arguments.Count, "Invalid argument count." ); Assert.AreEqual( true, request.Arguments[ 0 ].AsBoolean() ); Assert.AreEqual( "Test", request.Arguments[ 1 ].AsString() ); Assert.IsTrue( request.Arguments[ 2 ].IsArray ); var argments = request.Arguments[ 2 ].AsList(); Assert.AreEqual( 1, argments[ 0 ].AsInt32() ); Assert.AreEqual( 2, argments[ 1 ].AsInt32() ); Assert.AreEqual( 3, argments[ 2 ].AsInt32() ); e.Reply( requestId, new MessagePackObject( "Hello, world!" ) ); } catch ( SocketException ex ) { if ( ex.SocketErrorCode != SocketError.OperationAborted ) { Console.Error.WriteLine( "{0}:{1}", ex.SocketErrorCode, ex ); exceptionOnServer = ex; } } catch ( Exception ex ) { Console.Error.WriteLine( ex ); exceptionOnServer = ex; } finally { serverDone.Set(); } }; var options = new RpcClientOptions(); options.ForceIPv4 = true; RpcErrorMessage? error = null; using ( var eventLoop = new IOCompletionPortClientEventLoop( options, ( sender, e ) => error = e.RpcError, null ) ) { RpcClient client = RpcClient.CreateTcp( new IPEndPoint( IPAddress.Loopback, 57129 ), eventLoop, options ); var ar = client.BeginCall( "Test", new object[] { true, "Test", new int[] { 1, 2, 3 } }, null, null ); serverDone.Wait(); if ( exceptionOnServer != null ) { throw new AssertionException( "Server error.", exceptionOnServer ); } var result = client.EndCall( ar ); if ( error != null ) { Assert.Fail( error.Value.ToString() ); } Assert.AreEqual( "Hello, world!", result.AsString() ); } } }