/// <summary> /// The start game. /// </summary> private static void StartGame() { if (stopped) { return; } gameCounter++; string gameName = baseGameName + gameCounter; var clients = new List <ClientConnection>(Settings.NumClientsPerGame); games.Add(gameName, clients); for (int i = 0; i < Settings.NumClientsPerGame; i++) { var client = ClientConnectionFactory.GetClientConnection(Settings.PhotonApplication, gameName, i); client.Start(); clients.Add(client); // don't start all at once, that would not be realistic int sleep = random.Next((int)(Settings.StartupInterval * 0.5), (int)(Settings.StartupInterval * 1.5)); Thread.Sleep(sleep); } log.InfoFormat("[{2}] Started game {1} with {0} clients", Settings.NumClientsPerGame, gameName, Process.GetCurrentProcess().Id); if (Settings.TimeInGame > 0) { fiber.Schedule(() => StopGame(gameName), (long)TimeSpan.FromSeconds(Settings.TimeInGame).TotalMilliseconds); } }
private void recConn() { //topic需要与发布端topic一致 info = new ClientInfo(); info.setUser("MDT.Tools", "test"); //设置AMQIII的IP地址和端口号,可根据实际情况进行设置 info.setAddress("192.168.2.122/mq.httpMQTunnel", 19990); info.Protocol = ClientInfo.PROTOCOL_HTTP; try { info.LoginMessage = getLoginMsg("admin", "UOBS", "111111", ""); // 创建连接 conn = ClientConnectionFactory.createConnection(info); conn.addEventListener(this); conn.setLoginListener(this); conn.start(); // 订阅topic,接收消息 session = conn.createSession(); } catch (Exception e) { LogHelper.Error(e); } }
public async Task ClientConnectionOutgoingAbortCanEndLifeTime() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true, logChecker: logs => { Assert.Equal(2, logs.Count); Assert.Equal("SendLoopStopped", logs[0].Write.EventId.Name); Assert.Equal("ApplicationTaskFailed", logs[1].Write.EventId.Name); return(true); })) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var services = new ServiceCollection(); var connectionHandler = new EndlessConnectionHandler(); services.AddSingleton(connectionHandler); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <EndlessConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); var clientConnectionId = Guid.NewGuid().ToString(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); clientConnection.CancelOutgoing(); await clientConnection.LifetimeTask.OrTimeout(); // complete reading to end the connection transportConnection.Application.Output.Complete(); // 1s for application task to timeout await connectionTask.OrTimeout(1000); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); Assert.Empty(ccm.ClientConnections); connectionHandler.CancellationToken.Cancel(); } }
public async Task TestServiceConnectionWithEndlessApplicationTaskNeverEnds() { var clientConnectionId = Guid.NewGuid().ToString(); using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true, logChecker: logs => { Assert.Single(logs); Assert.Equal("DetectedLongRunningApplicationTask", logs[0].Write.EventId.Name); Assert.Equal($"The connection {clientConnectionId} has a long running application logic that prevents the connection from complete.", logs[0].Write.Message); return(true); })) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var services = new ServiceCollection(); var connectionHandler = new EndlessConnectionHandler(); services.AddSingleton(connectionHandler); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <EndlessConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null, null, closeTimeOutMilliseconds: 1); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); // complete reading to end the connection transportConnection.Application.Output.Complete(); // Assert timeout var lifetime = clientConnection.LifetimeTask; var task = await Task.WhenAny(lifetime, Task.Delay(1000)); Assert.NotEqual(lifetime, task); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); // since the service connection ends, the client connection is cleaned up from the collection... Assert.Empty(ccm.ClientConnections); } }
public async Task ClientConnectionWithDiagnosticClientTagTest() { using (StartVerifiableLog(out var loggerFactory)) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var diagnosticClientConnectionId = "diagnosticClient"; var normalClientConnectionId = "normalClient"; var services = new ServiceCollection(); var connectionHandler = new DiagnosticClientConnectionHandler(diagnosticClientConnectionId); services.AddSingleton(connectionHandler); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <DiagnosticClientConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(diagnosticClientConnectionId, null, new Dictionary <string, StringValues> { { Constants.AsrsIsDiagnosticClient, "true" } }, null))); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(normalClientConnectionId, null))); var connections = await Task.WhenAll(ccm.WaitForClientConnectionAsync(normalClientConnectionId).OrTimeout(), ccm.WaitForClientConnectionAsync(diagnosticClientConnectionId).OrTimeout()); await Task.WhenAll(from c in connections select c.LifetimeTask.OrTimeout()); // complete reading to end the connection transportConnection.Application.Output.Complete(); // 1s for application task to timeout await connectionTask.OrTimeout(1000); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); Assert.Empty(ccm.ClientConnections); } }
public void Start() { var factory = ClientConnectionFactory.CreateConnection("localhost"); this.channel = factory.CreateModel(); channel.QueueDeclare("HostQueue", true, false, false, null); consumer = ConsumerFactory.CreateConsumer(channel, "HostQueue", Consumer_Received); }
public async Task TestServiceConnectionWithNormalApplicationTask() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var services = new ServiceCollection(); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <TestConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); var clientConnectionId = Guid.NewGuid().ToString(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new CloseConnectionMessage(clientConnectionId))); // Normal end with close message await ccm.WaitForClientConnectionRemovalAsync(clientConnectionId).OrTimeout(); // another connection comes in clientConnectionId = Guid.NewGuid().ToString(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); // complete reading to end the connection transportConnection.Application.Output.Complete(); await connectionTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); Assert.Empty(ccm.ClientConnections); } }
static void Main() { Console.WriteLine("Application Start"); Guid senderUniqueId = Guid.NewGuid(); bool booleanValueToChangeMessage = false; while (true) { booleanValueToChangeMessage = !booleanValueToChangeMessage; var message = MakeMessage(senderUniqueId, booleanValueToChangeMessage); ClientConnectionFactory.Send("HostQueue", message); Console.WriteLine($"Sending message id {message.Id}"); Task.Delay(5000).Wait(); } }
public void Connect(ClientInfo info) { try { log.Info(com.adaptiveMQ2.utils.Consts.VERSION); this.clientInfo = info; _conn = ClientConnectionFactory.createConnection(info); _conn.addEventListener(this); if (info.LoginMessage != null) { _conn.setLoginListener(this); } _conn.start(); } catch (Exception ex) { log.Error(ex); } }
public bool TryConnect() { lock (syncRoot) { if (IsConnected) { return(true); } connection = ClientConnectionFactory.CreateConnection(settings.HostName); if (IsConnected) { connection.ConnectionShutdown += OnConnectionShutdown; connection.CallbackException += OnCallbackException; connection.ConnectionBlocked += OnConnectionBlocked; return(true); } return(false); } }
static void Main(string[] args) { //RabbitMQ Console.WriteLine("--- [RabbitMQ] ---"); var mqF = new ClientConnectionFactory(Helper.GetMQParam()); var clientProxy = NetRpcManager.CreateClientProxy <IService>(mqF, false); clientProxy.Connected += (s, e) => Console.WriteLine("[event] Connected"); clientProxy.DisConnected += (s, e) => Console.WriteLine("[event] DisConnected"); clientProxy.ExceptionInvoked += (s, e) => Console.WriteLine("[event] ExceptionInvoked"); //Heartbeat clientProxy.Heartbeat += async s => { Console.WriteLine("[event] Heartbeat"); s.Proxy.Hearbeat(); }; clientProxy.StartHeartbeat(true); _proxy = clientProxy.Proxy; _proxyAsync = NetRpcManager.CreateClientProxy <IServiceAsync>(mqF, false).Proxy; RunTest(); RunTestAsync().Wait(); //Grpc Console.WriteLine("\r\n--- [Grpc] ---"); var grpcF = new NetRpc.Grpc.ClientConnectionFactory(new Channel("localhost", 50001, ChannelCredentials.Insecure)); _proxy = NetRpc.Grpc.NetRpcManager.CreateClientProxy <IService>(grpcF).Proxy; _proxyAsync = NetRpc.Grpc.NetRpcManager.CreateClientProxy <IServiceAsync>(grpcF).Proxy; RunTest(); RunTestAsync().Wait(); Console.WriteLine("Test end."); Console.Read(); }
public RMQConnectionManager(RMQSettings settings) { this.settings = settings; connection = ClientConnectionFactory.CreateConnection(settings.HostName); }
public async Task ClientConnectionContextAbortCanSendOutCloseMessage() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace, expectedErrors: c => true, logChecker: logs => { return(true); })) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var services = new ServiceCollection(); var lastWill = "This is the last will"; var connectionHandler = new LastWillConnectionHandler(lastWill); services.AddSingleton(connectionHandler); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <LastWillConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); var clientConnectionId = Guid.NewGuid().ToString(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); await clientConnection.LifetimeTask.OrTimeout(); transportConnection.Transport.Output.Complete(); var input = await transportConnection.Application.Input.ReadAsync(); var buffer = input.Buffer; var canParse = protocol.TryParseMessage(ref buffer, out var msg); Assert.True(canParse); var message = msg as ConnectionDataMessage; Assert.NotNull(message); Assert.Equal(clientConnectionId, message.ConnectionId); Assert.Equal(lastWill, Encoding.UTF8.GetString(message.Payload.First.ToArray())); // complete reading to end the connection transportConnection.Application.Output.Complete(); // 1s for application task to timeout await connectionTask.OrTimeout(1000); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); Assert.Empty(ccm.ClientConnections); } }
public ConnectionPool(ClientConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; }
public ConnectionPool(ClientConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; }
public async Task TestServiceConnectionWithErrorApplicationTask() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true, logChecker: logs => { Assert.Equal(2, logs.Count); Assert.Equal("SendLoopStopped", logs[0].Write.EventId.Name); Assert.Equal("ApplicationTaskFailed", logs[1].Write.EventId.Name); return(true); })) { var ccm = new TestClientConnectionManager(); var ccf = new ClientConnectionFactory(); var protocol = new ServiceProtocol(); TestConnection transportConnection = null; var connectionFactory = new TestConnectionFactory(conn => { transportConnection = conn; return(Task.CompletedTask); }); var services = new ServiceCollection(); var errorTcs = new TaskCompletionSource <Exception>(); var connectionHandler = new ErrorConnectionHandler(errorTcs); services.AddSingleton(connectionHandler); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler <ErrorConnectionHandler>(); ConnectionDelegate handler = builder.Build(); var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf, "serverId", Guid.NewGuid().ToString("N"), null, null); var connectionTask = connection.StartAsync(); // completed handshake await connection.ConnectionInitializedTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); var clientConnectionId = Guid.NewGuid().ToString(); await transportConnection.Application.Output.WriteAsync( protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }))); var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout(); errorTcs.SetException(new InvalidOperationException("error operation")); await clientConnection.LifetimeTask.OrTimeout(); // Should complete the connection when application throws await ccm.WaitForClientConnectionRemovalAsync(clientConnectionId).OrTimeout(); // Application task should not affect the underlying service connection Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); // complete reading to end the connection transportConnection.Application.Output.Complete(); await connectionTask.OrTimeout(); Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status); Assert.Empty(ccm.ClientConnections); } }
public async Task<IServiceHubContext> CreateHubContextAsync(string hubName, ILoggerFactory loggerFactory = null, CancellationToken cancellationToken = default) { loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; switch (_serviceManagerOptions.ServiceTransportType) { case ServiceTransportType.Persistent: { var connectionFactory = new ManagementConnectionFactory(_productInfo, new ConnectionFactory(_serverNameProvider, loggerFactory)); var serviceProtocol = new ServiceProtocol(); var clientConnectionManager = new ClientConnectionManager(); var clientConnectionFactory = new ClientConnectionFactory(); ConnectionDelegate connectionDelegate = connectionContext => Task.CompletedTask; var serviceConnectionFactory = new ServiceConnectionFactory(serviceProtocol, clientConnectionManager, connectionFactory, loggerFactory, connectionDelegate, clientConnectionFactory); var weakConnectionContainer = new WeakServiceConnectionContainer( serviceConnectionFactory, _serviceManagerOptions.ConnectionCount, new HubServiceEndpoint(hubName, _endpointProvider, _endpoint), loggerFactory?.CreateLogger(nameof(WeakServiceConnectionContainer)) ?? NullLogger.Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSignalRCore(); serviceCollection.AddSingleton<IConfigureOptions<HubOptions>, ManagementHubOptionsSetup>(); if (loggerFactory != null) { serviceCollection.AddSingleton(typeof(ILoggerFactory), loggerFactory); } serviceCollection .AddLogging() .AddSingleton(typeof(IConnectionFactory), sp => connectionFactory) .AddSingleton(typeof(HubLifetimeManager<>), typeof(WebSocketsHubLifetimeManager<>)) .AddSingleton(typeof(IServiceConnectionManager<>), typeof(ServiceConnectionManager<>)) .AddSingleton(typeof(IServiceConnectionContainer), sp => weakConnectionContainer); var success = false; ServiceProvider serviceProvider = null; try { serviceProvider = serviceCollection.BuildServiceProvider(); var serviceConnectionManager = serviceProvider.GetRequiredService<IServiceConnectionManager<Hub>>(); serviceConnectionManager.SetServiceConnection(weakConnectionContainer); _ = serviceConnectionManager.StartAsync(); // wait until service connection established await weakConnectionContainer.ConnectionInitializedTask.OrTimeout(cancellationToken); var webSocketsHubLifetimeManager = (WebSocketsHubLifetimeManager<Hub>)serviceProvider.GetRequiredService<HubLifetimeManager<Hub>>(); var hubContext = serviceProvider.GetRequiredService<IHubContext<Hub>>(); var serviceHubContext = new ServiceHubContext(hubContext, webSocketsHubLifetimeManager, serviceProvider); success = true; return serviceHubContext; } finally { if (!success) { serviceProvider?.Dispose(); } } } case ServiceTransportType.Transient: { var serviceCollection = new ServiceCollection(); serviceCollection.AddSignalRCore(); // remove default hub lifetime manager var serviceDescriptor = serviceCollection.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(HubLifetimeManager<>)); serviceCollection.Remove(serviceDescriptor); // add rest hub lifetime manager var restHubLifetimeManager = new RestHubLifetimeManager(_serviceManagerOptions, hubName, _productInfo); serviceCollection.AddSingleton(typeof(HubLifetimeManager<Hub>), sp => restHubLifetimeManager); var serviceProvider = serviceCollection.BuildServiceProvider(); var hubContext = serviceProvider.GetRequiredService<IHubContext<Hub>>(); return new ServiceHubContext(hubContext, restHubLifetimeManager, serviceProvider); } default: throw new ArgumentException("Not supported service transport type."); } }