Esempio n. 1
0
        private void ShowConnections()
        {
            ClientPool aux = new ClientPool();

            Console.WriteLine("IP_ADDRESS             |    ID");
            Console.Write(aux.ToString());
        }
Esempio n. 2
0
        public void AClientCanSendAMessage()
        {
            var msgWait = new ManualResetEvent(false);

            var inMemoryStore = new InMemoryStore(new SingleClientTestPeer(msgWait));
            var clientPool    = new ClientPool();

            var server = new Server(inMemoryStore, clientPool);

            Task.Run(() => server.Start());

            var aClient = new TcpClient();

            aClient.Connect(IPAddress.Parse("127.0.0.1"), 10000);

            Assert.That(aClient.GetStream().CanWrite);

            var message   = $"Hello, World!{Environment.NewLine}";
            var msgBuffer = Encoding.ASCII.GetBytes(message);

            aClient.GetStream().Write(msgBuffer, 0, msgBuffer.Length);

            msgWait.WaitOne();

            StringAssert.AreEqualIgnoringCase(message, inMemoryStore.Read().First().Value);
        }
Esempio n. 3
0
        private void SendToAll(object obj, string topic, string controller)
        {
            //Get existing or create a new instance, then call the controller
            var location = string.Format("ws://{0}:{1}", HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port);

            ClientPool.GetInstance(location, "http://localhost").Send(obj, topic, controller);
        }
Esempio n. 4
0
 /// <summary>
 /// Only work for tcp
 /// </summary>
 protected virtual void OnConnected()
 {
     if (!ClientPool.ContainsKey(Session.RemoteIPEndPoint))
     {
         ClientPool.TryAdd(Session.RemoteIPEndPoint, this);
     }
 }
Esempio n. 5
0
        private static async Task <SpannerClient> GetSpannerClientAsync(ClientPool pool)
        {
            //immediately yield to increase contention for stress testing.
            await Task.Yield();

            return(await pool.AcquireClientAsync(s_defaultConnectionStringBuilder));
        }
Esempio n. 6
0
        protected void AcceptCallBack(IAsyncResult ar)
        {
            Socket client = Listener.EndAccept(ar);
            int    index  = ClientPool.Get();

            if (index >= 0)
            {
                ClientPool[index].SetActive();
                Connection con = ClientPool[index];
                con.clientId = index;
                StepMessage  = new byte[ClientPool.Count][];
                //for (int i = 0; i < StepMessage.Length; i++)
                //{
                //    StepMessage[i] = new byte[framSize];
                //}
                con.socket = client;
                SendIninInfo((byte)con.clientId);
                if (FrameList.Count > 0)
                {
                    SendToClientAllFrame(index);
                }
                con.socket.BeginReceive(con.readBuff, 0, Connection.buffer_size, SocketFlags.None, ReceiveCallBack, con);
            }
            else
            {
                ServerLog.LogServer("服务器人数达到上限", 0);
            }
            Listener.BeginAccept(AcceptCallBack, Listener);
        }
Esempio n. 7
0
        public async Task SequentialCreatesOnlyUseOneChannel()
        {
            //SpannerClients if created sequentially should only use a single channel.
            //This is to faciliate good session pool hits (which is per channel).  If we always
            //round robin'd clients, then we would get hard cache misses until we populated all
            //of the caches per channel.
            //Since channels are lazily created, this also saves resources for scenarios like rich clients
            //that may only need a single session for multiple sequential workloads.
            //Our default setting for # channels = 4 needs to work well for all scenarios.
            var firstReturnedClient = new Mock <SpannerClient>();
            var mockClientFactory   = SetupMockClientFactory(firstReturnedClient);

            var testPool       = new ClientPool(mockClientFactory);
            var expectedClient = firstReturnedClient.Object;

            Assert.Same(expectedClient, await testPool.AcquireClientAsync(s_defaultConnectionStringBuilder));
            testPool.ReleaseClient(expectedClient, s_defaultConnectionStringBuilder);

            Assert.Same(expectedClient, await testPool.AcquireClientAsync(s_defaultConnectionStringBuilder));
            testPool.ReleaseClient(expectedClient, s_defaultConnectionStringBuilder);

            Assert.Same(expectedClient, await testPool.AcquireClientAsync(s_defaultConnectionStringBuilder));
            testPool.ReleaseClient(expectedClient, s_defaultConnectionStringBuilder);

            var s = new StringBuilder();

            Assert.Equal(0, testPool.GetPoolInfo(s));
            Logger.DefaultLogger.Info(() => s.ToString());
            Assert.Equal(1, mockClientFactory.Invocations);
        }
Esempio n. 8
0
        public async Task ConcurrencyStress()
        {
            const int multiplier        = 10;
            var       mockClientFactory = SetupMockClientFactory();

            //A mini stress test that hits the client pool with multiple concurrent client requests.
            var concurrentQueries = new List <Task <SpannerClient> >();
            var testPool          = new ClientPool(mockClientFactory);

            for (var i = 0; i < SpannerOptions.Instance.MaximumGrpcChannels * multiplier; i++)
            {
                concurrentQueries.Add(GetSpannerClientAsync(testPool));
            }

            await Task.WhenAll(concurrentQueries);

            Assert.Equal(SpannerOptions.Instance.MaximumGrpcChannels, mockClientFactory.Invocations);

            var grouping = concurrentQueries.GroupBy(x => x.Result).ToList();

            Assert.Equal(SpannerOptions.Instance.MaximumGrpcChannels, grouping.Count);
            foreach (var group in grouping)
            {
                Assert.Equal(multiplier, group.Count());
            }

            foreach (var client in concurrentQueries.Select(x => x.Result))
            {
                testPool.ReleaseClient(client, s_defaultConnectionStringBuilder);
            }
            var s = new StringBuilder();

            Assert.Equal(0, testPool.GetPoolInfo(s));
            Logger.DefaultLogger.Info(() => s.ToString());
        }
Esempio n. 9
0
 /// <summary>
 /// Generate the client ppol
 /// </summary>
 void CreateClientPool()
 {
     while (this.Staff.Counter.ready == false)
     {
     }
     this.CltPool = new ClientPool();
 }
Esempio n. 10
0
        public void PullClientInfo(VirCli[] syncInfo)
        {
            if (syncInfo != null)
            {
                int len = syncInfo.Length;
                if (len <= 0)
                {
                    return;
                }

                for (int i = 0; i < len; ++i)
                {
                    VirCli sync = syncInfo[i];

                    VirtualClient client = null;
                    ClientStatus  status = (ClientStatus)Enum.ToObject(typeof(ClientStatus), sync.curStatus);

                    bool found = ClientPool.TryGetValue(sync.ClientID, out client);
                    if (found)
                    {
                        client.curStatus = status;
                    }
                    else
                    {
                        ClientPool[sync.ClientID] = new VirtualClient()
                        {
                            ClientID  = sync.ClientID,
                            curStatus = status,
                        };
                    }
                }
            }
        }
Esempio n. 11
0
        protected void SendStepAll(object sender, ElapsedEventArgs e)
        {
            if (ClientPool.ActiveCount <= 0)
            {
                if (FrameList.Count > 0)
                {
                    ServerLog.LogServer("所有客户端退出游戏 战斗结束!!!", 1);
                    FrameList.Clear();
                }
                return;
            }

            if (FrameList.Count == 0)
            {
                ServerLog.LogServer("玩家进入服务器 战斗开始!!!", 1);
            }
            ServerLog.LogServer("0[" + FrameList.Count + "]", 1);

            byte[][]     temp     = StepMessage;
            int          length   = temp.Length;
            ProtocolBase protocol = new ByteProtocol();

            protocol.push((byte)MessageType.Frame);
            protocol.push((byte)length);
            //ServerLog.LogServer("获取[" + FrameList.Count + "]", 1);
            for (int i = 0; i < length; i++)
            {
                protocol.push(temp[i] != null);
                protocol.push(temp[i]);
            }
            if (FrameList.Count == 0)
            {
                protocol.push((byte)MessageType.RandomSeed);
                Random rand = new Random();
                protocol.push(rand.Next(10000));
            }
            protocol.push((byte)MessageType.end);
            ServerLog.LogServer("生成帧信息[" + length + "]", 1);
            byte[] temp2 = protocol.GetByteStream();

            FrameList.Add(temp2);

            ClientPool.Foreach((con) => { SendToClient(con.clientId, temp2);
                                          if (!con.ActiveCheck())
                                          {
                                              ServerLog.LogClient("客户端断线 中止连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);

                                              con.socket.Close();
                                              ClientPool.Recover(con.clientId);
                                          }
                               });

            ServerLog.LogServer("帧同步[" + FrameList.Count + "]", 2);
            //StepMessage = new byte[ClientPool.Count][];
            //for (int i = 0; i < StepMessage.Length; i++)
            //{
            //    StepMessage[i] = new byte[framSize];
            //}
        }
Esempio n. 12
0
 /// <summary>
 /// Only work for tcp
 /// </summary>
 protected virtual void OnDisconnected()
 {
     if (ClientPool.ContainsKey(Session.RemoteIPEndPoint))
     {
         ClientPool.Remove(Session.RemoteIPEndPoint);
     }
     Dispose();
 }
Esempio n. 13
0
        public void Maximum_One_Aquire_Single_Object()
        {
            var obj        = new object();
            var clientPool = new ClientPool <object>(1, () => obj);

            var aquired = clientPool.Aquire();

            Assert.AreSame(obj, aquired);
        }
Esempio n. 14
0
        private void KillConnection()
        {
            Console.Write("Client ID to kill: ");
            string     s   = Console.ReadLine();
            ClientPool aux = new ClientPool();

            aux.KillClient(s);
            Console.WriteLine("Killed: " + s);
        }
Esempio n. 15
0
 /// <summary>
 /// Check if the udp client is expired,
 /// this method will only be invoked by UdpServer
 /// </summary>
 private void CheckExpiredClient()
 {
     // we calculate the interval between last packe and current time
     if (((IUdpSession)Session).SessionExistedTime > _expireTimeInterval)
     {
         ClientPool.Remove(((IUdpSession)Session).RemoteIPEndPoint);
         Dispose();
     }
 }
Esempio n. 16
0
 public FastlyActionHandler()
 {
     clients = new ClientPool <string, HttpClient>(key =>
     {
         return(new HttpClient
         {
             Timeout = TimeSpan.FromSeconds(2)
         });
     });
 }
Esempio n. 17
0
        /// <summary>
        /// Generate the client ppol
        /// </summary>
        void CreateClientPool()
        {
            while (this.Staff.Counter.ready == false)
            {
            }
            Console.WriteLine("Create client pool");
            ClientPool CltPool = new ClientPool();

            Clients = CltPool.ClientGroups;
            //StaffManager.Instance().ClientPool = CltPool;
        }
Esempio n. 18
0
        protected void ReceiveCallBack(IAsyncResult ar)
        {
            Connection con = (Connection)ar.AsyncState;

            if (!con.ActiveCheck())
            {
                return;
            }
            try
            {
                lock (con)
                {
                    int length = con.socket.EndReceive(ar);
                    ServerLog.LogClient("receive:" + length, 1, con.clientId);
                    if (length <= 0)
                    {
                        ServerLog.LogClient("客户端断开连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);

                        con.socket.Close();
                        ClientPool.Recover(con.clientId);

                        return;
                    }
                    con.length += length;
                    //Console.WriteLine("bool isNew = bufferList[con]:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId);
                    //bool isNew = bufferList[con] == null;
                    ProcessData(con);

                    //{
                    //    //MessageList.Push(message);

                    //    bufferList[con] = null;
                    //}
                    //else
                    //{
                    //    bufferList[con] = message;
                    ////}
                    //Console.WriteLine("接收信息:" + message.Length + "ClientID:" + con.clientId);



                    con.socket.BeginReceive(con.readBuff, con.length, con.BuffRemain, SocketFlags.None, ReceiveCallBack, con);
                }
            }
            catch (Exception)
            {
                ServerLog.LogClient("客户端异常终止连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);

                con.socket.Close();
                ClientPool.Recover(con.clientId);
                //throw;
            }
        }
Esempio n. 19
0
        public void AClientCanConnect()
        {
            var clientPool = new ClientPool();
            var server     = new Server(new NoStore(), clientPool);

            Task.Run(() => server.Start());

            var aClient = new TcpClient();

            aClient.Connect(IPAddress.Parse("127.0.0.1"), 10000);
            Assert.That(clientPool.GetConnectedClients(), Has.Count.EqualTo(1));
        }
Esempio n. 20
0
        public void Maximum_One_Aquire_Single_Object_DiscardBusyClient_calls_Free_action()
        {
            var    obj        = new object();
            object freeObject = null;
            var    clientPool = new ClientPool <object>(1, () => obj, x => freeObject = x);

            var aquired = clientPool.Aquire();

            clientPool.DiscardBusyClient(aquired);

            Assert.AreSame(obj, freeObject);
        }
Esempio n. 21
0
 public void OnHeartBeat(string clientID)
 {
     if (!string.IsNullOrEmpty(clientID))
     {
         VirtualClient client = null;
         bool          setOk  = ClientPool.TryGetValue(clientID, out client);
         if (setOk)
         {
             client.HeartTick = stopwatch.ElapsedMilliseconds;
         }
     }
 }
Esempio n. 22
0
 public ClientBase(ISession session)
 {
     Session = session;
     EventBinding();
     lock (ClientPool)
     {
         // we fire this when there are no record in Sessions
         if (!ClientPool.ContainsKey(session.RemoteIPEndPoint))
         {
             ClientPool.Add(Session.RemoteIPEndPoint, this);
         }
     }
 }
Esempio n. 23
0
        public GameListener(int numConnections, int asyncBufferSize)
        {
            m_numConnections = numConnections;

            m_UserTokenPool            = new ClientPool <UserToken>(numConnections);
            m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);

            for (int i = 0; i < m_numConnections; i++) //按照连接数建立读写对象
            {
                UserToken userToken = new UserToken(asyncBufferSize);
                m_UserTokenPool.Push(userToken);
            }
        }
Esempio n. 24
0
        public SlackActionHandler(RuleEventFormatter formatter)
        {
            Guard.NotNull(formatter, nameof(formatter));

            this.formatter = formatter;

            clients = new ClientPool <string, HttpClient>(key =>
            {
                return(new HttpClient
                {
                    Timeout = TimeSpan.FromSeconds(2)
                });
            });
        }
        private void EndAccept(IAsyncResult ar)
        {
            var listener = ListenSocket.EndAccept(ar);
            var connId   = Guid.NewGuid().ToString();
            var args     = ClientPool.Take();

            args.AcceptSocket = listener;
            args.UserToken    = ServerConnectionFactory.Create(this, connId);
            args.LastResponse = DateTime.UtcNow.AddMinutes(1);
            listener.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, EndReceive, args);
            ListenSocket.BeginAccept(EndAccept, ListenArgs);
            ClientsToSocket.TryAdd(connId, args);
            OnClientConnectedInvoke((ServerConnectionBase)args.UserToken);
        }
Esempio n. 26
0
 public Server(int port)
 {
     if (server == null)
     {
         server      = new TcpListener(IPAddress.Any, port);
         _clientPool = new ClientPool();
         server.Start();
         StartListener();
     }
     else
     {
         Console.WriteLine("Server already started.\n");
     }
 }
Esempio n. 27
0
        public bool QuitJoin(JoinInfo joinin)
        {
            bool setOk = false;

            if (joinin != null)
            {
                VirtualClient client = null;
                setOk = ClientPool.TryGetValue(joinin.ClientID, out client);

                if (setOk)
                {
                    CharactorPool.QuitRoom(joinin.Charactor);

                    //申请写锁
                    readerWriterLock.EnterWriteLock();
                    ClientPool.Remove(joinin.ClientID);
                    //释放写锁
                    readerWriterLock.ExitWriteLock();

                    ConnectedClientCount -= 1;
                    if (client.curStatus.check(ClientStatus.Ready))
                    {
                        ReadyClientCount -= 1;
                    }
                    if (client.curStatus.check(ClientStatus.UIReady))
                    {
                        UIReadyClientCount -= 1;
                    }

                    //guard
                    if (ConnectedClientCount < 0)
                    {
                        ConnectedClientCount = 0;
                    }
                    if (ReadyClientCount < 0)
                    {
                        ReadyClientCount = 0;
                    }
                    if (UIReadyClientCount < 0)
                    {
                        UIReadyClientCount = 0;
                    }

                    AsyncClient();
                }
            }

            return(setOk);
        }
Esempio n. 28
0
 void AssingPort(int offset)
 {
     // We cannot modify a static dictionary in parallel evaluation!
     // We call it before, from ParallelGenomeListEvaluator
     //UpdateUserToPortDictionary();
     myPort = userToPort[userName];
     myPort = myPort + offset;
     //WriteToLog("Adding client info, port: " + myPort + " requested by user " + userName);
     clientPool = null;
     clientPool = new ClientPool();
     clientPool.add(new ClientInfo("127.0.0.1", myPort));
     System.Diagnostics.Debug.WriteLine("Creating a clientPool with number: " + myPort);
     //clientPool.add(new ClientInfo("127.0.0.1", 10000));
     // We always add 10005 as an extra as the last resource!
     clientPool.add(new ClientInfo("127.0.0.1", 10005));
 }
Esempio n. 29
0
        public async Task ClientsCreatedOnDemandAsync()
        {
            //SpannerClients should not be precreated, but be created lazily.
            var mockClientFactory = SetupMockClientFactory();

            var testPool       = new ClientPool(mockClientFactory);
            var clientAcquired = await testPool.AcquireClientAsync(s_defaultConnectionStringBuilder);

            testPool.ReleaseClient(clientAcquired, s_defaultConnectionStringBuilder);

            Assert.Equal(1, mockClientFactory.Invocations);
            var s = new StringBuilder();

            Assert.Equal(0, testPool.GetPoolInfo(s));
            Logger.DefaultLogger.Info(() => s.ToString());
        }
Esempio n. 30
0
        public WebhookActionHandler(RuleEventFormatter formatter)
        {
            Guard.NotNull(formatter, nameof(formatter));

            this.formatter = formatter;

            clients = new ClientPool <string, HttpClient>(key =>
            {
                var client = new HttpClient
                {
                    Timeout = TimeSpan.FromSeconds(4)
                };

                client.DefaultRequestHeaders.Add("User-Agent", "Squidex Webhook");

                return(client);
            });
        }
Esempio n. 31
0
        private void runMission(MissionSpec mission)
        {
            string recordPath = "none";
            MissionRecordSpec missionRecord;
            if (string.IsNullOrEmpty(Settings.Default.OutputDir))
            {
                missionRecord = new MissionRecordSpec();
            }
            else
            {
                recordPath = Path.Combine(Settings.Default.OutputDir, Guid.NewGuid() + ".tar.gz");
                missionRecord = new MissionRecordSpec(recordPath);
                if (Settings.Default.RecordObservations)
                {
                    missionRecord.recordObservations();
                }

                if (Settings.Default.RecordRewards)
                {
                    missionRecord.recordRewards();
                }

                if (Settings.Default.RecordCommands)
                {
                    missionRecord.recordCommands();
                }

                if (Settings.Default.RecordMP4)
                {
                    missionRecord.recordMP4(Settings.Default.MP4FPS, (long)(Settings.Default.BitRate * 1024));
                }
            }

            using (AgentHost agentHost = new AgentHost())
            {
                ClientPool clientPool = new ClientPool();
                clientPool.add(new ClientInfo(Settings.Default.ClientIP, Settings.Default.ClientPort));

                try
                {
                    agentHost.startMission(mission, clientPool, missionRecord, 0, "hac");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error Starting Mission", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                Dispatcher.Invoke(() =>
                {
                    Activate();
                    VideoImage.Focus();
                    startB.Content = "Set";
                    Title = Settings.Default.Title + " : Waiting for mission start";
                    if (_recordWindow != null && _recordWindow.IsVisible)
                    {
                        _recordWindow.RecordPath = recordPath;
                    }
                });

                _isInSession = true;
                try
                {
                    WorldState worldState;
                    // wait for mission to start
                    do
                    {
                        Thread.Sleep(100);
                        worldState = agentHost.getWorldState();

                        if (worldState.errors.Any())
                        {
                            StringBuilder errors = new StringBuilder();
                            foreach (TimestampedString error in worldState.errors)
                            {
                                errors.AppendLine(error.text);
                            }

                            MessageBox.Show(errors.ToString(), "Error during mission initialization", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    while (!worldState.is_mission_running && !_stopMission);

                    if (_stopMission)
                    {
                        return;
                    }

                    DateTime missionStartTime = DateTime.UtcNow;
                    _timeRemaining = _missionDuration;

                    Dispatcher.Invoke(() =>
                    {
                        startB.Content = "Go!";
                        Title = Settings.Default.Title + " : Recording";
                    });

                    // run mission
                    TimeSpan loopTime = TimeSpan.FromSeconds(1.0 / 20);

                    _pendingCommandsMutex.Wait();
                    try
                    {
                        _pendingCommandQueue = new Queue<Tuple<string, float>>();
                    }
                    finally
                    {
                        _pendingCommandsMutex.Release();
                    }

                    _pendingMessagesMutex.Wait();
                    try
                    {
                        _pendingMessages = new Queue<string>();
                    }
                    finally
                    {
                        _pendingMessagesMutex.Release();
                    }

                    bool failure = false;
                    Stopwatch loopTimer = new Stopwatch();
                    do
                    {
                        loopTimer.Reset();
                        loopTimer.Start();

                        worldState = agentHost.getWorldState();

                        TimestampedVideoFrame frame = worldState.video_frames.FirstOrDefault();

                        if (frame != null)
                        {
                            if (_missionDuration != TimeSpan.Zero)
                            {
                                TimeSpan elapsed = frame.timestamp - missionStartTime;
                                _timeRemaining = _missionDuration - elapsed;
                            }

                            _pixelsMutex.Wait();
                            try
                            {
                                if (_pixels == null || _pixels.Length != frame.pixels.Count)
                                {
                                    _pixels = new byte[frame.pixels.Count];
                                    Dispatcher.Invoke(() =>
                                    {
                                        if (_bitmap.Width != frame.width || _bitmap.Height != frame.height)
                                        {
                                            _bitmap = new WriteableBitmap(frame.width, frame.height, 72, 72, PixelFormats.Rgb24, null);
                                            VideoImage.Source = _bitmap;
                                            if (_recordWindow != null && _recordWindow.IsVisible)
                                            {
                                                _recordWindow.FrameSource = _bitmap;
                                            }
                                        }
                                    });
                                }

                                frame.pixels.CopyTo(_pixels);
                            }
                            finally
                            {
                                _pixelsMutex.Release();
                            }
                        }

                        _pendingMessagesMutex.Wait();
                        try
                        {
                            foreach (var reward in worldState.rewards)
                            {
                                _score += reward.getValue();
                                if (reward.getValue() < 0)
                                {
                                    failure = true;
                                }

                                _pendingMessages.Enqueue(string.Format("{0}> score {1}", reward.timestamp.ToString("hh:mm:ss.fff"), reward.getValue()));
                            }

                            _score = Math.Max(_score, 0);
                            _score = Math.Min(_score, 99999);

                            foreach (var observation in worldState.observations)
                            {
                                int posStart = observation.text.IndexOf("\"XPos\"");
                                if (posStart < 0)
                                {
                                    continue;
                                }

                                int posEnd = observation.text.IndexOf("\"ZPos\"");
                                posEnd = observation.text.IndexOf(',', posEnd);

                                string posSegment = observation.text.Substring(posStart, posEnd - posStart);
                                string[] pos = posSegment.Split(',');
                                float x = Convert.ToSingle(pos[0].Split(':')[1]);
                                float y = Convert.ToSingle(pos[1].Split(':')[1]);
                                float z = Convert.ToSingle(pos[2].Split(':')[1]);

                                _pendingMessages.Enqueue(string.Format("{0}> (x={1:0.00}, y={2:0.00}, z={3:0.00})", observation.timestamp.ToString("hh:mm:ss.fff"), x, y, z));
                            }
                        }
                        finally
                        {
                            _pendingMessagesMutex.Release();
                        }

                        CheckGamepad(agentHost);

                        _pendingCommandsMutex.Wait();
                        try
                        {
                            while (_pendingCommandQueue.Any())
                            {
                                var command = _pendingCommandQueue.Dequeue();
                                CheckAndSend(agentHost, command.Item1, command.Item2);
                            }
                        }
                        finally
                        {
                            _pendingCommandsMutex.Release();
                        }

                        loopTimer.Stop();
                        if (loopTimer.Elapsed < loopTime)
                        {
                            Thread.Sleep(loopTime - loopTimer.Elapsed);
                        }

                    } while (worldState.is_mission_running && !_stopMission);

                    if (_stopMission)
                    {
                        return;
                    }

                    if (!failure)
                    {
                        _score += _timeRemaining.TotalSeconds * 100;
                    }

                    _missionSuccess = !failure;

                    _pendingCommandsMutex.Wait();
                    try
                    {
                        _pendingCommandQueue = null;
                    }
                    finally
                    {
                        _pendingCommandsMutex.Release();
                    }

                    Dispatcher.Invoke(() =>
                    {
                        Title = Settings.Default.Title + " : Ready";
                        UpdateDisplayedMessages();
                        UpdateDisplayedReward();
                    });

                    _resetVerb = null;

                    var keys = _continuousCommandState.Keys.ToList();
                    foreach (var verb in keys)
                    {
                        _continuousCommandState[verb] = 0;
                    }

                    keys = _discreteCommandState.Keys.ToList();
                    foreach (var verb in keys)
                    {
                        _discreteCommandState[verb] = false;
                    }

                    if (worldState.errors.Any())
                    {
                        StringBuilder errors = new StringBuilder();
                        foreach (TimestampedString error in worldState.errors)
                        {
                            errors.AppendLine(error.text);
                        }

                        MessageBox.Show(errors.ToString(), "Error during mission initialization", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error during mission", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                finally
                {
                    _isInSession = false;
                }
            }
        }