示例#1
0
        /// <summary>
        /// Handles this server sessions spawn.
        /// </summary>
        /// <param name="sender">Local session.</param>
        /// <param name="e">Formal junk.</param>
        private void RoutingServer_SessionSpawned(object sender, EventArgs e)
        {
            var session = sender as ActiveSession <T>;

            session.End             += Session_End;
            session.IsClientSide     = true;
            session.ExceptionThrown += AllTargets_ExceptionThrown;
            session.MessageReceived += Session_MessageReceived;
            var servers = new List <ActiveEndPoint <T> >();

            for (int i = 0, n = Targets.Length; i < n; i++)
            {
                var remote = new ActiveEndPoint <T>(Targets[i], session)
                {
                    Index = i
                };
                remote.ExceptionThrown += AllTargets_ExceptionThrown;
                remote.MessageReceived += Remote_MessageReceived;
                remote.SessionClosed   += Remote_SessionClosed;
                servers.Add(remote);
            }
            session.Remotes     = servers.ToArray();
            session.Route       = RouteDefault;
            session.IsBroadcast = IsBroadcast;
            SessionStarted?.Invoke(session, EventArgs.Empty);
            foreach (var server in session.Remotes)
            {
                server.Connect();
            }
            if (!session.Remotes.All(i => i.IsConnected))
            {
                session.Close();
            }
        }
示例#2
0
        /// <summary>
        /// Finishes the break and resumes current task
        /// </summary>
        public void Resume()
        {
            // Stop the break
            EndBreak();

            // Launch session if has not been yet started
            if (!mSecondsTicker.Enabled)
            {
                // Update timestamp
                mStartTime = DateTime.Now;
                // Start first task
                StartNextTask(mCurrentTask);
                // Broadcast session is started
                SessionStarted.Invoke();
                // Do not perform any other action
                return;
            }

            // If current task is already finished... (the case when user opted for break when task's time ended)
            if (CurrentTimeLeft <= TimeSpan.Zero)
            {
                // Fire finish command
                Finish();
                return;
            }

            // Recalculate remaining tasks after break
            RecalculateTasksAfterBreak();
        }
示例#3
0
        private void EventBasedNetListenerOnNetworkReceiveEvent(NetPeer peer, NetDataReader reader)
        {
            //Not the used connector = end
            if (!IsConnected)
            {
                return;
            }

            DatagramPayload payload;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(reader.Data, 0, reader.AvailableBytes);
                memoryStream.Seek(0, SeekOrigin.Begin);
                payload = (DatagramPayload)_formatter.Deserialize(memoryStream);
            }

            SimulatorDataSet simulatorDataSet = _datagramPayloadUnPacker.UnpackDatagramPayload(payload);

            if (payload.PayloadKind == DatagramPayloadKind.SessionStart || _firstPackage)
            {
                _firstPackage = false;
                SessionStarted?.Invoke(this, new DataEventArgs(simulatorDataSet));
            }
            else
            {
                DataLoaded?.Invoke(this, new DataEventArgs(simulatorDataSet));
            }
        }
 private void GameStartedHandler(MainGameData gameData)
 {
     if (gameData != null)
     {
         SessionStarted?.Invoke(gameData);
     }
 }
示例#5
0
 private void EnsureSessionStarted(RequiredModel model)
 {
     if (model.Type != null &&
         _previousModel?.Type == null)
     {
         SessionStarted?.Invoke(this, model);
     }
 }
示例#6
0
 public void LogStart(SessionStarted e)
 {
     if (_writer != null)
     {
         return;
     }
     _writer = new LogFileWriter(TemporaryFile, TemporaryDirectory);
     _dataSource.MarkDirty();
 }
示例#7
0
        public void UpdateSessionBasics(SessionType type, SessionPhase phase)
        {
            if (phase == SessionPhase.None)
            {
                return;
            }

            if (_session == null)
            {
                _session = CreateSession(type);
                Logger.Log($"{type} session started - new weekend");
                SessionStarted?.Invoke(this, EventArgs.Empty);
            }
            else if (type != _session.Type)
            {
                if (IsInProgress(_session.Phase))
                {
                    EndTimedPhase();
                }

                Logger.Log($"{_session.Type} session ended");
                SessionEnded?.Invoke(this, EventArgs.Empty);

                var isPartOfWeekend = type > _session.Type;

                _session = isPartOfWeekend
          ? CreateSession(type, _session.WeekendId)
          : CreateSession(type);

                var message = isPartOfWeekend
          ? $"{type} session started - part of existing weekend"
          : $"{type} session started - new weekend";

                Logger.Log(message, Severity.Verbose);
                SessionStarted?.Invoke(this, EventArgs.Empty);
            }

            // We capture this so we the nested methods can use the up-to-date session
            var oldPhase = _session.Phase;

            _session.UpdateSessionInfo(type, phase);

            // If we are in the same session, check if we are advancing through the timed phases
            if (type == _session.Type)
            {
                if (IsStarting(oldPhase) && IsInProgress(_session.Phase))
                {
                    StartTimedPhase();
                }

                if (IsInProgress(oldPhase) && IsEnding(_session.Phase))
                {
                    EndTimedPhase();
                }
            }
        }
示例#8
0
        /// <summary>
        /// This method will let the AI play the maze for one game (windowless)
        /// </summary>
        public MazeCycleOutcome Travel(int timerTimeout = 5000)
        {
            MazeGame game = new MazeGame();

            game.traveler = this;
            game.InitGame(maze);

            MazeCycleOutcome outcome = new MazeCycleOutcome();

            // Start AI Training
            currentSessionID = rlmNet.SessionStart();

            SessionStarted?.Invoke(rlmNet.RandomnessCurrentValue);

            tmr.Interval = timerTimeout;
            tmr.Start();
            timeout = 0;
            int movesCnt = 0;

            while (!outcome.GameOver && timeout == 0)
            {
                // set up input for x and y based on our current location on the maze
                var inputs = new List <RlmIOWithValue>()
                {
                    new RlmIOWithValue(rlmNet.Inputs.First(a => a.Name == "X"), game.traveler.location.X.ToString()),
                    new RlmIOWithValue(rlmNet.Inputs.First(a => a.Name == "Y"), game.traveler.location.Y.ToString()),
                };

                // get AI output based on inputs
                RlmCycle cycle     = new RlmCycle();
                var      aiResult  = cycle.RunCycle(rlmNet, currentSessionID, inputs, Learn);
                var      direction = Convert.ToInt16(aiResult.CycleOutput.Outputs.First().Value);

                // make the move
                outcome = game.CycleMaze(direction);

                // score AI output
                double score = ScoreAI(outcome, game.traveler);
                rlmNet.ScoreCycle(aiResult.CycleOutput.CycleID, score);

                MazeCycleComplete?.Invoke(game.traveler.location.X, game.traveler.location.Y, outcome.BumpedIntoWall);
                movesCnt++;
            }

            tmr.Stop();

            // compute final score
            outcome.FinalScore = game.CalculateFinalScore(game.Moves);

            // End AI Training
            rlmNet.SessionEnd(outcome.FinalScore);

            SessionComplete?.Invoke(rlmNet.SessionCount, outcome.FinalScore, movesCnt);

            return(outcome);
        }
示例#9
0
        protected override async Task SessionBeginInternal()
        {
            startTime             = DateTime.Now;
            lastSessionUpdateTime = startTime;
            SessionTimerStart();
            SessionStarted?.Invoke(null, EventArgs.Empty);

            Metrics metrics = new Metrics(DeviceData.OS, null, null, null, null, AppVersion, DeviceData.Locale);

            await AddSessionEvent(new BeginSession(AppKey, await DeviceData.GetDeviceId(), sdkVersion, metrics));
        }
示例#10
0
        private IEnumerator StartSessionCoroutine()
        {
            //Wait one frame so components that want to subcribe to
            //SessionStarted event can be initialized after game scene
            //being loaded
            yield return(null);

            IsSessionActive = true;
            //Session has started now, notify other components
            SessionStarted?.Invoke();
        }
示例#11
0
        void HandleSessionStartedMessage(SessionStarted message)
        {
            Player challenger = GetPlayerById(message.ChallengerId);
            Player challenged = GetPlayerById(message.ChallengedId);

            if (challenger == null || challenged == null)
            {
                return;
            }

            Dispatcher.Instance.Enqueue(() => GameManager.Instance.StartSession(message.SessionId, challenger, challenged));
        }
示例#12
0
        /// <summary>
        /// Initializes a new Session
        /// </summary>
        /// <param name="AutoStart">(optional) also start the set automatically</param>
        public void StartSession(bool AutoStart = false)
        {
            Debug.Log("Session Starting");
            currentSetCount    = 0;
            currentBreathCount = 0;
            timeBreathpaused   = 0;
            isSessionStarted   = true;

            SessionStarted?.Invoke(this);

            if (AutoStart)
            {
                StartSet();
            }
        }
示例#13
0
        private void RaiseSessionStartedEvent(SimulatorDataSet data)
        {
            DataEventArgs args = new DataEventArgs(data);

            Logger.Info("New Session starting");
            if (_oldDataSet != null)
            {
                Logger.Info("Old set:");
                LogSimulatorDataSet(_oldDataSet);
            }

            _oldDataSet = data;
            Logger.Info("New set:");
            LogSimulatorDataSet(_oldDataSet);
            SessionStarted?.Invoke(this, args);
        }
示例#14
0
        private void RaiseSessionStartedEvent(SimulatorDataSet data)
        {
            DataEventArgs args = new DataEventArgs(data);

            Logger.Info("New Session starting" + data.SessionInfo.SessionType);

            /*if (_oldDataSet != null)
             * {
             *  Logger.Info("Old set:");
             *  LogSimulatorDataSet(_oldDataSet);
             * }
             *
             * _oldDataSet = data;
             * Logger.Info("New set:");
             * LogSimulatorDataSet(_oldDataSet);*/
            SessionStarted?.Invoke(this, args);
        }
示例#15
0
        public async Task <EventSession> StartSessionAsync(TraceProfileDescriptor descriptor)
        {
            if (runningSession != null)
            {
                throw new InvalidOperationException("Session already in progress.");
            }

            var traceLog = new TraceLog();
            var session  = new EventSession(descriptor, traceLog);

            SessionStarting?.Invoke(traceLog);

            await session.StartAsync();

            runningSession = session;
            SessionStarted?.Invoke(runningSession);
            return(session);
        }
示例#16
0
文件: Proxy.cs 项目: HTD/Woof.Sockets
        /// <summary>
        /// Handles this server sessions spawn.
        /// </summary>
        /// <param name="sender">Local session.</param>
        /// <param name="e">Formal junk.</param>
        private void ProxyServer_SessionSpawned(object sender, EventArgs e)
        {
            var session = sender as ActiveSession <T>;

            session.End             += Session_End;
            session.IsClientSide     = true;
            session.ExceptionThrown += Session_ExceptionThrown;
            session.MessageReceived += Session_MessageReceived;
            var remote = new ActiveEndPoint <T>(A, session);

            remote.MessageReceived += Remote_MessageReceived;
            remote.ExceptionThrown += Session_ExceptionThrown;
            session.Remotes         = new[] { remote };
            SessionStarted?.Invoke(this, EventArgs.Empty);
            remote.Connect();
            if (!remote.IsConnected)
            {
                session.Close();
            }
        }
示例#17
0
        void HandleAcceptChallengeMessage(AcceptChallenge message)
        {
            ServerPlayer player = GetPlayerBySecret(message.Secret);

            if (player == null)
            {
                return;
            }

            Challenge accepted = null;

            foreach (Challenge challenge in _challenges)
            {
                if (challenge.Challenged.Id != player.Id)
                {
                    continue;
                }

                ServerPlayer challenger = GetPlayerById(challenge.Challenger.Id);
                ServerPlayer challenged = GetPlayerById(challenge.Challenged.Id);

                GameState session = new GameState(NextSessionId, challenger.CreateGamePlayer(), challenged.CreateGamePlayer());
                _sessions[session.Id] = session;

                var sessionStarted = new SessionStarted(session.Id, challenger.Id, challenged.Id);

                BaseServer.SendTo(challenger.NetPlayer, sessionStarted);
                BaseServer.SendTo(challenged.NetPlayer, sessionStarted);
                accepted = challenge;

                Task.Run(() => RunGame(session).ConfigureAwait(false));

                break;
            }

            if (accepted != null)
            {
                _challenges.Remove(accepted);
            }
        }
示例#18
0
        public IGameSession Add(IBotServer server, Guid sessionId, string userId, string username, DateTime created)
        {
            lock (sessionMutex)
            {
                var existingSession = sessions.FirstOrDefault(x => x.Id == sessionId);
                if (existingSession != null)
                {
                    if (SessionStarted != null)
                    {
                        SessionStarted.Invoke(this, existingSession);
                    }

                    return(existingSession);
                }

                var session = new RavenfallGameSession(server, sessionId, userId, username, created);
                sessions.Add(session);
                if (SessionStarted != null)
                {
                    SessionStarted.Invoke(this, session);
                }
                return(session);
            }
        }
 private void GameStartedHandler(MainGameData gameData)
 {
     print($"[SESSION] Started");
     SessionStarted?.Invoke(gameData);
 }
示例#20
0
 protected void OnSessionStarted()
 {
     SessionStarted?.Invoke(this);
 }
示例#21
0
 public void OnSessionStarted(ActiveSession s)
 {
     SessionStarted?.Invoke(s);
 }
示例#22
0
 public void LogStart(SessionStarted e)
 {
     if (_writer != null) return;
     _writer = new LogFileWriter(TemporaryFile, TemporaryDirectory);
     _dataSource.MarkDirty();
 }
示例#23
0
 protected virtual void OnDataSessionStarted(DataManagerEventArgs e)
 {
     SessionStarted?.Invoke(this, e);
 }
 private void Session_Started(object sender, EventArgs e)
 {
     RaiseSessionStatusChangedAndTrace(MeterSessionStatus.SessionStarted, "#Sesión Iniciada. Estableciendo Conexión");
     SessionStarted?.Invoke(this, new EventArgs());
 }
    public void RestartSession()
    {
        Data.Session.Reset();

        SessionStarted?.Invoke();
    }
示例#26
0
        /// <summary>
        /// Starts Processing Commands
        /// </summary>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A Task which performs the operation</returns>
        public async override Task StartAsync(CancellationToken cancellationToken)
        {
            // Validate Port before starting
            if (Port == 0)
            {
                throw new Exception("Invalid port number");
            }

            // Initializes Server
            try
            {
                Server = new TcpListener(IPAddress.Any, Port);
                Server.Start(10);

                // Notify the listening started
                ListeningStarted?.Invoke(this, new ListeningStartedEventArgs(Port));

                while (cancellationToken.IsCancellationRequested == false)
                {
                    // Keep listening for incoming connections
                    var client = await Server.AcceptTcpClientAsync().WithCancellation(cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    // Creates the Communication Session
                    var sessionID = this.BeginSession();

                    // Notify that a session is started
                    var sessionStartedEventArgs = new SessionStartedEventArgs(sessionID);
                    SessionStarted?.Invoke(this, sessionStartedEventArgs);

                    // Make sure session is not denied
                    if (sessionStartedEventArgs.Deny)
                    {
                        // Session is denied, unregister it
                        this.EndSession(sessionID);
                    }
                    else
                    {
                        // Session is allowed, continue with it
                        var networkCommunicationSession = new NetworkCommunicationSession(client, sessionID, ShowTimer, ShowPrompt);
                        networkCommunicationSession.RawCommandReceived += (sender, commandEventArgs) =>
                        {
                            // Executes the command and waits for the answer
                            var taskResponse = Task.Run <CommandExecutionResponse>(async() => await ExecuteCommandAsync(networkCommunicationSession.ID, commandEventArgs.RawCommand));
                            var response     = taskResponse.Result;

                            // Outputs the response
                            commandEventArgs.Response = this.ResponseFormatter.Format(response);

                            // Replace "\n" by the environment NewLine
                            commandEventArgs.Response = commandEventArgs.Response.Replace("\n", System.Environment.NewLine);
                        };

                        // Add session to the collection
                        lock (NetworkCommunicationSessionsLock)
                        {
                            NetworkCommunicationSessions.Add(networkCommunicationSession.ID, networkCommunicationSession);
                        }

#pragma warning disable 4014

                        // Run Communication Session
                        networkCommunicationSession.RunAsync(cancellationToken).ContinueWith(t =>
                        {
                            // Stop Session
                            networkCommunicationSession.Stop();

                            // Remove Session from Internal Controls
                            lock (NetworkCommunicationSessionsLock)
                            {
                                NetworkCommunicationSessions.Remove(networkCommunicationSession.ID);
                            }

                            // Unregister session with the Command Processor
                            this.EndSession(networkCommunicationSession.ID);

                            // Call SessionEnded event
                            SessionEnded?.Invoke(this, new SessionEndedEventArgs(networkCommunicationSession.ID));
                        }, cancellationToken);

#pragma warning restore 4014
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (Server != null)
                {
                    Server.Stop();
                }
            }
        }
示例#27
0
 void StartSession()
 {
     StopAllCoroutines();
     SessionStarted?.Invoke();
 }
示例#28
0
        /// <summary>
        ///     Starts a new <see cref="Session"/> with the specified <paramref name="userName"/> and <paramref name="password"/>
        /// </summary>
        /// <param name="userName">The user for which the Session is to be started.</param>
        /// <param name="password">The password with which to authenticate the user.</param>
        /// <returns>A Result containing the result of the operation and the created Session.</returns>
        public IResult <ISession> StartSession(string userName, string password)
        {
            logger.EnterMethod(xLogger.Params(userName, xLogger.Exclude()));
            logger.Info($"Starting Session for User '{userName}'...");

            IResult <ISession> retVal = new Result <ISession>();

            if (State != State.Running)
            {
                retVal.AddError($"The Manager is not in a state in which it can service requests (Currently {State}).");
            }
            else
            {
                IUser foundUser = FindUser(userName);

                if (foundUser != default(User))
                {
                    string hash = SDK.Common.Utility.ComputeSHA512Hash(password);

                    if (foundUser.PasswordHash == hash)
                    {
                        ISession foundSession = FindUserSession(foundUser.Name);

                        if (foundSession == default(Session))
                        {
                            retVal.ReturnValue = SessionFactory.CreateSession(foundUser, Configuration.SessionLength);

                            sessionLock.EnterWriteLock();

                            try
                            {
                                SessionList.Add(retVal.ReturnValue);
                            }
                            finally
                            {
                                sessionLock.ExitWriteLock();
                            }
                        }
                        else
                        {
                            retVal.AddWarning($"The specified User has an existing Session.  The existing Session is being returned.");
                            retVal.ReturnValue = foundSession;
                        }
                    }
                    else
                    {
                        retVal.AddError($"Supplied password does not match.");
                    }
                }
                else
                {
                    retVal.AddError($"User '{userName}' does not exist.");
                }
            }

            if (retVal.ResultCode != ResultCode.Failure)
            {
                if (retVal.ResultCode == ResultCode.Success)
                {
                    Task.Run(() => SessionStarted?.Invoke(this, new SessionEventArgs(retVal.ReturnValue)));
                }
            }

            retVal.LogResult(logger);
            logger.ExitMethod(retVal);
            return(retVal);
        }
示例#29
0
        private MazeCycleOutcome Travel(bool learn, int?timerTimeout = null, CancellationToken?token = null, bool perMoveDisplay = false)
        {
            IMazeGame game = GetNewGameInstance();

            MazeCycleOutcome outcome = new MazeCycleOutcome();

            // Start AI Training
            var currentSessionID = network.SessionStart();

            SessionStarted?.Invoke(network.RandomnessCurrentValue);

            recentMoves.Clear();

            //tmr.Interval = timerTimeout;
            //tmr.Start();
            //timeout = 0;
            int movesCnt = 1;

            while (!outcome.GameOver) // && timeout == 0)
            {
                if (token?.IsCancellationRequested == true)
                {
                    break;
                }

                // set up input for x and y based on our current location on the maze
                var inputs = new List <RlmIOWithValue>()
                {
                    //new RlmIOWithValue(network.Inputs.First(a => a.Name == "X"), game.traveler.location.X.ToString()),
                    //new RlmIOWithValue(network.Inputs.First(a => a.Name == "Y"), game.traveler.location.Y.ToString()),
                    new RlmIOWithValue(network.Inputs.First(a => a.Name == "Move"), movesCnt.ToString())
                };

                // get AI output based on inputs
                RlmCycle cycle     = new RlmCycle();
                var      aiResult  = cycle.RunCycle(network, currentSessionID, inputs, learn);
                var      direction = Convert.ToInt16(aiResult.CycleOutput.Outputs.First().Value);

                // make the move
                outcome = game.CycleMaze(direction);


                // score AI output
                double score = 0.0;
                //score = ScoreAI(outcome, game.traveler);
                network.ScoreCycle(aiResult.CycleOutput.CycleID, score);

                if (timerTimeout.HasValue)
                {
                    Task.Delay(timerTimeout.Value).Wait();
                }

                if (perMoveDisplay)
                {
                    MazeCycleComplete?.Invoke(game.traveler.location.X, game.traveler.location.Y, outcome.BumpedIntoWall);
                }

                if (!learn)
                {
                    recentMoves.Add(new MoveDetails()
                    {
                        Direction = direction, MoveNumber = movesCnt
                    });
                }

                movesCnt++;
            }

            //tmr.Stop();

            // compute final score
            outcome.FinalScore = game.CalculateFinalScore(game.Moves);

            // End AI Training
            network.SessionEnd(outcome.FinalScore);

            SessionComplete?.Invoke(network.SessionCount, outcome.FinalScore, movesCnt - 1);

            if (movesCnt > HighestMoveCount)
            {
                HighestMoveCount = movesCnt;
            }

            return(outcome);
        }
示例#30
0
 /// <summary>
 /// Called whenever the <see cref="Session"/> has been started.
 /// </summary>
 /// <remarks>
 /// <remarks>
 /// In order for this override and properties like <see cref="IsSessionStarted"/>
 /// to be tracked correctly, use the <see cref="StartSessionAsync"/> and
 /// <see cref="StopSession"/> methods rather than calling methods
 /// directly on the <see cref="Session"/> instance.
 /// </remarks>
 protected virtual void OnSessionStarted()
 {
     SessionStarted?.Invoke(this, EventArgs.Empty);
 }
示例#31
0
        //public async Task<bool> ReleaseSession(string sessionId)
        //{
        //    if (pool.TryGet(sessionId, out var session)) {
        //        await session.ReleaseAsync();
        //        OnSessionReleased(session);
        //        return true;
        //    }

        //    return false;
        //}

        protected void OnSessionStarted(ServerSessionBase session)
        {
            SessionStarted?.Invoke(this, new SessionStateEventArgs(session));
        }