예제 #1
0
 private static void OnStopSessionMessageReceived(StopSessionMessage message)
 {
     if (ProxySessionManager.TryGet(message.SessionId, out ProxySession session))
     {
         ClientConnectionManager.Disconnect(session.ClientConnection, message.Reason);
     }
 }
예제 #2
0
        public async Task ServiceConnectionDispatchOpenConnectionToUnauthorizedHubTest()
        {
            bool ExpectedErrors(WriteContext writeContext)
            {
                return(writeContext.LoggerName == typeof(ServiceConnection).FullName &&
                       writeContext.EventId == new EventId(11, "ConnectedStartingFailed") &&
                       writeContext.Exception.Message == "Unable to authorize request");
            }

            using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrors: ExpectedErrors))
            {
                var hubConfig = new HubConfiguration();
                var ccm       = new ClientConnectionManager(hubConfig, loggerFactory);
                hubConfig.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
                using (var proxy = new TestServiceConnectionProxy(ccm, loggerFactory: loggerFactory))
                {
                    // start the server connection
                    await proxy.StartServiceAsync().OrTimeout();

                    var clientConnection = Guid.NewGuid().ToString("N");

                    // Application layer sends OpenConnectionMessage to an authorized hub from anonymous user
                    var openConnectionMessage = new OpenConnectionMessage(clientConnection, new Claim[0], null, "?transport=webSockets&connectionData=%5B%7B%22name%22%3A%22authchat%22%7D%5D");
                    await proxy.WriteMessageAsync(openConnectionMessage);

                    await proxy.WaitForClientConnectAsync(clientConnection).OrTimeout();

                    // Verify client connection is not created due to authorized failure.
                    ccm.TryGetServiceConnection(clientConnection, out var serviceConnection);
                    Assert.Null(serviceConnection);
                }
            }
        }
        public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExisted()
        {
            var serviceConnectionManager = new TestServiceConnectionManager <TestHub>();
            var clientConnectionManager  = new ClientConnectionManager();

            var context    = new ClientConnectionContext(new OpenConnectionMessage("conn1", new Claim[] { }));
            var connection = new TestServiceConnectionPrivate();

            context.ServiceConnection = connection;
            clientConnectionManager.AddClientConnection(context);

            var manager = MockLifetimeManager(serviceConnectionManager, clientConnectionManager);

            await manager.SendConnectionAsync("conn1", "foo", new object[] { 1, 2 });

            Assert.NotNull(connection.LastMessage);
            if (connection.LastMessage is MultiConnectionDataMessage m)
            {
                Assert.Equal("conn1", m.ConnectionList[0]);
                Assert.Equal(1, m.Payloads.Count);
                Assert.True(m.Payloads.ContainsKey(MockProtocol));
                return;
            }
            Assert.True(false);
        }
 private void Init()
 {
     _connectionManager        = _client.GetConnectionManager();
     _clientMembershipListener = new ClientMembershipListener(_client);
     _connectionManager.AddConnectionListener(this);
     _credentials = _client.GetClientConfig().GetCredentials();
 }
예제 #5
0
파일: Program.cs 프로젝트: BjkGkh/R106
        static void Main(string[] args)
        {
            Console.WindowHeight = Console.LargestWindowHeight - 20;
            Console.WindowWidth = Console.LargestWindowWidth - 20;
            Helpers.Out.startLogger(); //START LOGING!!
            ConnectionManager.SocketManager man = new ConnectionManager.SocketManager();
            man.init(9001, 1337, 10, new GamePacketParser(), true);
            man.connectionEvent += new ConnectionManager.SocketManager.ConnectionEvent(man_connectionEvent);
            man.initializeConnectionRequests();

            string s;
            ipcon = new ClientConnectionManager("127.0.0.1", 9001);
            ipcon.OnConnectionChange += new ClientConnectionManager.connectionChanged(ipcon_OnConnectionChange);

            while((s = Console.ReadLine()) != "exit")
            {
                switch (s)
                {
                    case "con":
                        {
                            ipcon.openConnection();
                            break;
                        }
                    case "p":
                        {
                            ipcon.processSyncedMessages();
                            break;
                        }
                }
            }
            ipcon.Dispose();
            man.destroy();
            Out.stopLogger();
        }
예제 #6
0
 public ClientMembershipListener(HazelcastClient client)
 {
     _client            = client;
     _connectionManager = (ClientConnectionManager)client.GetConnectionManager();
     _partitionService  = (ClientPartitionService)client.GetClientPartitionService();
     _clusterService    = (ClientClusterService)client.GetClientClusterService();
 }
예제 #7
0
        public InventoryPredict(ClientConnectionManager connection, List <StockRecord> items, int selected)
        {
            InitializeComponent();
            _connection = connection;
            _items      = items;

            List <int> IDs = new List <int>();

            foreach (StockRecord s in _items)
            {
                cmb_name.Items.Add(s.StockName);
            }

            if ((selected >= 0) && (selected < _items.Count))
            {
                cmb_name.SelectedIndex = selected;
            }

            cmb_name.Enabled = false;

            IDs.Add(_items[selected].StockID);

            txt_sales.Text   = PredictSales(IDs).ToString();
            txt_profits.Text = PredictProfit(IDs).ToString();
        }
예제 #8
0
        public async Task ServiceConnectionDispatchOpenConnectionToUnauthorizedHubTest()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true, logChecker:
                                      logs =>
            {
                Assert.Single(logs);
                Assert.Equal("ConnectedStartingFailed", logs[0].Write.EventId.Name);
                Assert.Equal("Unable to authorize request", logs[0].Write.Exception.Message);
                return(true);
            }))
            {
                var hubConfig = new HubConfiguration();
                var ccm       = new ClientConnectionManager(hubConfig, loggerFactory);
                hubConfig.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
                using (var proxy = new TestServiceConnectionProxy(ccm, loggerFactory: loggerFactory))
                {
                    // start the server connection
                    await proxy.StartServiceAsync().OrTimeout();

                    var connectionId = Guid.NewGuid().ToString("N");
                    var connectTask  = proxy.WaitForOutgoingMessageAsync(connectionId).OrTimeout();

                    // Application layer sends OpenConnectionMessage to an authorized hub from anonymous user
                    var openConnectionMessage = new OpenConnectionMessage(connectionId, new Claim[0], null, "?transport=webSockets&connectionData=%5B%7B%22name%22%3A%22authchat%22%7D%5D");
                    await proxy.WriteMessageAsync(openConnectionMessage);

                    var message = await connectTask;

                    Assert.True(message is CloseConnectionMessage);

                    // Verify client connection is not created due to authorized failure.
                    Assert.False(ccm.ClientConnections.TryGetValue(connectionId, out var connection));
                }
            }
        }
        public async Task ServiceConnectionWithTransportLayerClosedShouldCleanupEndlessConnectClientConnections()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrors: c => true, logChecker:
                                      logs =>
            {
                var errorLogs = logs.Where(s => s.Write.LogLevel == LogLevel.Error).ToList();
                Assert.Single(errorLogs);
                Assert.Equal("ApplicationTaskTimedOut", errorLogs[0].Write.EventId.Name);

                return(true);
            }))
            {
                var hubConfig = Utility.GetActualHubConfig(loggerFactory);
                var appName   = "app1";
                var hub       = "EndlessConnect";
                var scm       = new TestServiceConnectionHandler();
                hubConfig.Resolver.Register(typeof(IServiceConnectionManager), () => scm);
                var ccm = new ClientConnectionManager(hubConfig, loggerFactory);
                hubConfig.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
                DispatcherHelper.PrepareAndGetDispatcher(new TestAppBuilder(), hubConfig,
                                                         new ServiceOptions {
                    ConnectionString = ConnectionString
                }, appName, loggerFactory);
                using (var proxy = new TestServiceConnectionProxy(ccm, loggerFactory))
                {
                    // start the server connection
                    var connectionTask = proxy.StartAsync();
                    await proxy.ConnectionInitializedTask.OrTimeout();

                    var clientConnection = Guid.NewGuid().ToString("N");

                    var connectTask = scm.WaitForTransportOutputMessageAsync(typeof(GroupBroadcastDataMessage))
                                      .OrTimeout();
                    // Application layer sends OpenConnectionMessage
                    var openConnectionMessage = new OpenConnectionMessage(clientConnection, new Claim[0], null,
                                                                          $"?transport=webSockets&connectionToken=conn1&connectionData=%5B%7B%22name%22%3A%22{hub}%22%7D%5D");
                    await proxy.WriteMessageAsync(openConnectionMessage);

                    var connectMessage = (await connectTask)as GroupBroadcastDataMessage;
                    Assert.NotNull(connectMessage);
                    Assert.Equal($"hg-{hub}.note", connectMessage.GroupName);

                    var message = connectMessage.Payloads["json"]
                                  .GetJsonMessageFromSingleFramePayload <HubResponseItem>();

                    Assert.Equal("Connected", message.A[0]);

                    // close transport layer
                    proxy.TestConnectionContext.Application.Output.Complete();

                    // wait for application task to timeout
                    await proxy.WaitForConnectionClose.OrTimeout(10000);

                    Assert.Equal(ServiceConnectionStatus.Disconnected, proxy.Status);

                    // cleaned up clearly
                    Assert.Empty(ccm.ClientConnections);
                }
            }
        }
        public async Task ServiceConnectionWithErrorDisconnectHub()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrors: c => true, logChecker:
                                      logs => true))
            {
                var hubConfig = Utility.GetActualHubConfig(loggerFactory);
                var appName   = "app1";
                var hub       = "ErrorDisconnect"; // error connect hub
                var scm       = new TestServiceConnectionHandler();
                hubConfig.Resolver.Register(typeof(IServiceConnectionManager), () => scm);
                var ccm = new ClientConnectionManager(hubConfig, loggerFactory);
                hubConfig.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
                DispatcherHelper.PrepareAndGetDispatcher(new TestAppBuilder(), hubConfig,
                                                         new ServiceOptions {
                    ConnectionString = ConnectionString
                }, appName, loggerFactory);
                using (var proxy = new TestServiceConnectionProxy(ccm, loggerFactory: loggerFactory))
                {
                    // start the server connection
                    await proxy.StartServiceAsync().OrTimeout();

                    var clientConnection = Guid.NewGuid().ToString("N");

                    var connectTask = scm.WaitForTransportOutputMessageAsync(typeof(GroupBroadcastDataMessage))
                                      .OrTimeout();
                    // Application layer sends OpenConnectionMessage
                    var openConnectionMessage = new OpenConnectionMessage(clientConnection, new Claim[0], null,
                                                                          $"?transport=webSockets&connectionToken=conn1&connectionData=%5B%7B%22name%22%3A%22{hub}%22%7D%5D");
                    await proxy.WriteMessageAsync(openConnectionMessage);

                    var connectMessage = (await connectTask)as GroupBroadcastDataMessage;
                    Assert.NotNull(connectMessage);
                    Assert.Equal($"hg-{hub}.note", connectMessage.GroupName);

                    var message = connectMessage.Payloads["json"]
                                  .GetJsonMessageFromSingleFramePayload <HubResponseItem>();

                    Assert.Equal("Connected", message.A[0]);

                    var disconnectTask = scm.WaitForTransportOutputMessageAsync(typeof(GroupBroadcastDataMessage))
                                         .OrTimeout();

                    await proxy.WriteMessageAsync(new CloseConnectionMessage(clientConnection));

                    var disconnectMessage = (await disconnectTask)as GroupBroadcastDataMessage;

                    Assert.NotNull(disconnectMessage);
                    Assert.Equal($"hg-{hub}.note", disconnectMessage.GroupName);

                    message = disconnectMessage.Payloads["json"]
                              .GetJsonMessageFromSingleFramePayload <HubResponseItem>();

                    Assert.Equal("Disconnected", message.A[0]);

                    // cleaned up clearly
                    Assert.Empty(ccm.ClientConnections);
                }
            }
        }
예제 #11
0
        public Inventory(ClientConnectionManager connection)
        {
            InitializeComponent();

            _connection = connection;

            UpdateList();
        }
예제 #12
0
        public void AddClientConnection(ClientConnectionContext clientConnection)
        {
            ClientConnectionManager.AddClientConnection(clientConnection);

            if (_waitForConnectionOpen.TryGetValue(clientConnection.ConnectionId, out var tcs))
            {
                tcs.TrySetResult(clientConnection);
            }
        }
        public ClientConnectionManagerTests()
        {
            var hubConfig = new HubConfiguration();
            var transport = new AzureTransportManager(hubConfig.Resolver);

            hubConfig.Resolver.Register(typeof(ITransportManager), () => transport);

            _clientConnectionManager = new ClientConnectionManager(hubConfig);
        }
예제 #14
0
        public void RemoveClientConnection(string connectionId)
        {
            ClientConnectionManager.RemoveClientConnection(connectionId);

            if (_waitForConnectionClose.TryGetValue(connectionId, out var tcs))
            {
                tcs.TrySetResult(null);
            }
        }
        public ServiceConnectionProxy(ConnectionDelegate callback = null, PipeOptions clientPipeOptions = null,
                                      Func <Func <TestConnection, Task>, TestConnectionFactory> connectionFactoryCallback = null, int connectionCount = 1)
        {
            ConnectionFactory          = connectionFactoryCallback?.Invoke(ConnectionFactoryCallbackAsync) ?? new TestConnectionFactory(ConnectionFactoryCallbackAsync);
            ClientConnectionManager    = new ClientConnectionManager();
            _clientPipeOptions         = clientPipeOptions;
            ConnectionDelegateCallback = callback ?? OnConnectionAsync;

            ServiceConnectionContainer = new StrongServiceConnectionContainer(this, ConnectionFactory, connectionCount, new ServiceEndpoint("", ""));
        }
예제 #16
0
    public override void ExecuteAiCommand(AiPlayer aiPlayer, ClientConnectionManager aiConnection)
    {
        //@TODO: Proper AI card selection
        int cardId = aiPlayer.m_cards[0].Key;

        aiPlayer.m_cards.RemoveAt(0);
        SGC_PlayCardFromHand command = new SGC_PlayCardFromHand(cardId);

        aiConnection.TransmitStream(command.PackCommand());
    }
예제 #17
0
파일: Sales.cs 프로젝트: raryin/dp2
        public Sales(ClientConnectionManager connection)
        {
            InitializeComponent();

            _connection = connection;

            _stockrecords = _connection.RequestStockInfo(-1);

            UpdateList();
        }
예제 #18
0
 /** Start an offline server within the application and start a game  */
 public void PlayOffline()
 {
     m_offline           = true;
     m_localServerRunner = new LocalServerRunner();
     m_client            = new ClientConnectionManager();
     m_localServerRunner.StartServer(m_client);
     if (m_client.IsConnected() && m_visualManager == null)  // Check for visual manager to know if we are already in-game - Hacky!!
     {
         SceneManager.LoadScene("Scenes/CardGame");
     }
 }
예제 #19
0
    public void ConnectButton()
    {
        m_client = new ClientConnectionManager();
        bool connected = m_client.AttemptConnection(m_ipAddress, m_port);

        if (connected)
        {
            // load new scene
            SceneManager.LoadScene("Scenes/CardGame");
        }
    }
예제 #20
0
 public override void ExecuteAiCommand(AiPlayer aiPlayer, ClientConnectionManager aiConnection)
 {
     if (m_playerID == aiPlayer.m_playerID)
     {
         aiPlayer.m_lifeTotal = m_life;
     }
     else
     {
         aiPlayer.m_opponentLifeTotal = m_life;
     }
 }
예제 #21
0
    public void StartServer(ClientConnectionManager connectionMgr)
    {
        m_clientConMgr = connectionMgr;
        m_aiConMgr     = new ClientConnectionManager();
        m_aiPlayer     = new AiPlayer();
        m_server       = new CardGameServer();

        InitializeServer();
        ConnectClients();
        RunServer();
    }
예제 #22
0
        public async Task ServiceConnectionDispatchGroupMessagesTest()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
            {
                var hubConfig = new HubConfiguration();
                hubConfig.Resolver = new DefaultDependencyResolver();
                var scm = new TestServiceConnectionManager();
                hubConfig.Resolver.Register(typeof(IServiceConnectionManager), () => scm);

                var ccm = new ClientConnectionManager(hubConfig);
                hubConfig.Resolver.Register(typeof(IClientConnectionManager), () => ccm);

                DispatcherHelper.PrepareAndGetDispatcher(new TestAppBuilder(), hubConfig, new ServiceOptions {
                    ConnectionString = ConnectionString
                }, "app1", loggerFactory);

                using (var proxy = new ServiceConnectionProxy(ccm, loggerFactory: loggerFactory))
                {
                    // start the server connection
                    await proxy.StartServiceAsync().OrTimeout();

                    var clientConnection = Guid.NewGuid().ToString("N");

                    // Application layer sends OpenConnectionMessage
                    var openConnectionMessage = new OpenConnectionMessage(clientConnection, new Claim[0], null, "?transport=webSockets&connectionToken=conn1");
                    await proxy.WriteMessageAsync(openConnectionMessage);

                    await proxy.WaitForClientConnectAsync(clientConnection).OrTimeout();

                    // group message goes into the manager
                    // make sure the tcs is called before writing message
                    var jgTask = scm.WaitForTransportOutputMessageAsync(typeof(JoinGroupMessage)).OrTimeout();
                    var gbTask = scm.WaitForTransportOutputMessageAsync(typeof(GroupBroadcastDataMessage)).OrTimeout();

                    await proxy.WriteMessageAsync(new ConnectionDataMessage(clientConnection, Encoding.UTF8.GetBytes("{\"H\":\"chat\",\"M\":\"JoinGroup\",\"A\":[\"user1\",\"message1\"],\"I\":1}")));

                    await jgTask;
                    await gbTask;

                    var lgTask = scm.WaitForTransportOutputMessageAsync(typeof(LeaveGroupMessage)).OrTimeout();
                    gbTask = scm.WaitForTransportOutputMessageAsync(typeof(GroupBroadcastDataMessage)).OrTimeout();

                    await proxy.WriteMessageAsync(new ConnectionDataMessage(clientConnection, Encoding.UTF8.GetBytes("{\"H\":\"chat\",\"M\":\"LeaveGroup\",\"A\":[\"user1\",\"message1\"],\"I\":1}")));

                    await lgTask;
                    await gbTask;

                    var dTask = proxy.WaitForClientDisconnectAsync(clientConnection).OrTimeout();
                    await proxy.WriteMessageAsync(new CloseConnectionMessage(clientConnection));

                    await dTask;
                }
            }
        }
예제 #23
0
        public ClientConnectionContext RemoveClientConnection(string connectionId)
        {
            var connection = ClientConnectionManager.RemoveClientConnection(connectionId);

            if (_waitForConnectionClose.TryGetValue(connectionId, out var tcs))
            {
                tcs.TrySetResult(null);
            }

            return(connection);
        }
        public ServiceConnectionTests(ITestOutputHelper output) : base(output)
        {
            var hubConfig     = new HubConfiguration();
            var protectedData = new EmptyProtectedData();
            var transport     = new AzureTransportManager(hubConfig.Resolver);

            hubConfig.Resolver.Register(typeof(IProtectedData), () => protectedData);
            hubConfig.Resolver.Register(typeof(ITransportManager), () => transport);

            _clientConnectionManager = new ClientConnectionManager(hubConfig);
        }
예제 #25
0
        public ServiceConnectionProxy(ConnectionDelegate callback = null, PipeOptions clientPipeOptions = null,
                                      Func <Func <TestConnection, Task>, TestConnectionFactory> connectionFactoryCallback = null, int connectionCount = 1)
        {
            ConnectionFactory          = connectionFactoryCallback?.Invoke(ConnectionFactoryCallbackAsync) ?? new TestConnectionFactory(ConnectionFactoryCallbackAsync);
            ClientConnectionManager    = new ClientConnectionManager();
            _clientPipeOptions         = clientPipeOptions;
            ConnectionDelegateCallback = callback ?? OnConnectionAsync;

            ServiceConnectionContainer = new StrongServiceConnectionContainer(this, connectionCount, new HubServiceEndpoint("", null, null), NullLogger.Instance);
            ServiceMessageHandler      = (StrongServiceConnectionContainer)ServiceConnectionContainer;
        }
예제 #26
0
        public InventoryEdit(ClientConnectionManager connection, List <StockRecord> items)
        {
            InitializeComponent();
            _connection = connection;
            _items      = items;

            foreach (StockRecord s in _items)
            {
                cmb_name.Items.Add(s.StockName);
            }
        }
예제 #27
0
    public override void ExecuteAiCommand(AiPlayer aiPlayer, ClientConnectionManager aiConnection)
    {
        // @TODO: AI implementation
        // Sending the same deck that the player loaded for now
        string     deckFileName = m_visualManager.GetDeckFileName();
        PackedDeck deck         = new PackedDeck();

        deck.LoadFromJSON(PackedDeck.deckPath + deckFileName);
        SGC_SendDeck command = new SGC_SendDeck(deck);

        m_visualManager.TransmitStream(command.PackCommand());
    }
예제 #28
0
 /// <summary>
 /// Creates a new MainServerConnection handeler with the given details
 /// </summary>
 /// <param name="ip">The ip address of the server</param>
 /// <param name="port">The port to connect to</param>
 public MainServerConnectionHolder(string ip, int port, string username, string license)
 {
     this.ip         = ip;
     this.port       = port;
     this.username   = username;
     this.serial     = license;
     keepThreadAlive = true;
     connection      = new ClientConnectionManager(ip, port);
     connection.OnConnectionChange += ConStatusChanged;
     aliveCheck = new Thread(DoHealthChecks);
     aliveCheck.Start();
 }
예제 #29
0
        private void Start()
        {
            if (started)
                return;

            this.SessionID = Guid.NewGuid().ToString();

            if (mgr == null)
                mgr = new ClientConnectionManager();

            mgr.Connect();
        }
예제 #30
0
        public ClientConnectionManagerTests()
        {
            var hubConfig = new HubConfiguration
            {
                Resolver = new DefaultDependencyResolver()
            };
            var transport = new AzureTransportManager(hubConfig.Resolver);

            hubConfig.Resolver.Register(typeof(ITransportManager), () => transport);

            _clientConnectionManager = new ClientConnectionManager(hubConfig, null);
        }
 public bool TryAddClientConnection(ClientConnectionContext connection)
 {
     if (ClientConnectionManager.TryAddClientConnection(connection))
     {
         if (_waitForConnectionOpen.TryGetValue(connection.ConnectionId, out var tcs))
         {
             tcs.TrySetResult(connection);
         }
         return(true);
     }
     return(false);
 }
 public bool TryRemoveClientConnection(string connectionId, out ClientConnectionContext connection)
 {
     if (ClientConnectionManager.TryRemoveClientConnection(connectionId, out connection))
     {
         if (_waitForConnectionClose.TryGetValue(connectionId, out var tcs))
         {
             tcs.TrySetResult(null);
         }
         return(true);
     }
     return(false);
 }
예제 #33
0
        private void Stop()
        {
            if (mgr != null)
                mgr.Close();

            mgr = null;
        }