private async Task PeerConnected(IScenePeerClient peer)
        {
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = await _sessions.GetUser(peer);

            if (user == null)
            {
                throw new ClientException("You are not authenticated.");
            }

            foreach (var uId in _clients.Keys)
            {
                if (uId != user.Id)
                {
                    var currentClient = _clients[uId];
                    peer.Send("player.update",
                              new PlayerUpdate {
                        UserId = uId, Status = (byte)currentClient.Status, Reason = currentClient.FaultReason ?? ""
                    },
                              PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE_ORDERED);
                }
            }
            if (_status == ServerStatus.Started)
            {
                peer.Send("server.started", new GameServerStartMessage {
                    Ip = _ip, Port = _port
                });
            }
        }
 public Task onConnected(IScenePeerClient client)
 {
     m_nbPlayer++;
     if (m_game != null && m_nbPlayer == m_game.MaxPlayer)
         m_started = true;
     return Task.FromResult(true);
 }
        public async Task PeerDisconnecting(IScenePeerClient peer)
        {
            if (IsHost(peer.SessionId))
            {
                lock (_lock)
                {
                    _serverPeer = null;
                }
            }
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = RemoveUserId(peer);

            _analytics.Push("gamesession", "playerLeft", JObject.FromObject(new { sessionId = peer.SessionId, gameSessionId = this._scene.Id }));
            Client client = null;
            string userId = null;

            // the peer disconnected from the app and is not in the sessions anymore.
            foreach (var kvp in _clients)
            {
                if (kvp.Value.Peer == peer)
                {
                    userId = kvp.Key;

                    if (_config.Public)
                    {
                        _clients.TryRemove(userId, out client);
                    }
                    // no need to continue searching for the client, we already found it
                    break;
                }
            }


            if (client != null)
            {
                client.Peer   = null;
                client.Status = PlayerStatus.Disconnected;

                BroadcastClientUpdate(client, userId);
                await EvaluateGameComplete();
            }

            if (_shutdownMode == ShutdownMode.NoPlayerLeft)
            {
                if (!_clients.Values.Any(c => c.Status != PlayerStatus.Disconnected))
                {
                    var _ = Task.Run(async() =>
                    {
                        await Task.Delay(1000 * 60);
                        if (!_clients.Values.Any(c => c.Status != PlayerStatus.Disconnected))
                        {
                            await CloseGameServerProcess();
                        }
                    });
                }
            }
        }
示例#4
0
 /// <summary>
 /// Sends a request to a scene that doesn't return data.
 /// </summary>
 /// <typeparam name="TData">The type of data to send.</typeparam>
 /// <param name="peer">The target peer.</param>
 /// <param name="route">The target route.</param>
 /// <param name="parameter">The request parameter.</param>
 /// <param name="priority">The request's priority level.</param>
 /// <returns>A task completing on request completion.</returns>
 public static async Task SendVoidRequest <TData>(this IScenePeerClient peer, string route, TData parameter, PacketPriority priority = PacketPriority.MEDIUM_PRIORITY)
 {
     await peer.Rpc(route, s =>
     {
         peer.Serializer().Serialize(parameter, s);
     }, priority).FirstOrDefaultAsync();
 }
        public Task OnConnected(IScenePeerClient client)
        {
            //var user = await _userSessions.GetUser(client);
            //var notifs = await _repository.GetPendingNotifications(user.Id);

            //var defaultDate = new DateTime();

            //var expiredNotifs = notifs.Where(n => n.ExpirationDate != defaultDate && n.ExpirationDate < DateTime.UtcNow).ToList();

            //if (expiredNotifs.Count > 0)
            //{
            //    await _repository.DeleteNotifications(expiredNotifs);
            //    notifs = notifs.Except(expiredNotifs);
            //}

            //if (notifs.Count() > 0)
            //{
            //    foreach (var notification in notifs)
            //    {
            //        client.Send("inappnotification.push", new InAppNotification(notification));
            //        if (notification.Acknowledgment == InAppNotificationAcknowledgment.OnSend)
            //        {
            //            var _ = AcknowledgeNotification(notification.Id); // don't await the notifications
            //        }
            //    }
            //}
            return(Task.CompletedTask);
        }
示例#6
0
        public Task OnConnected(IScenePeerClient peer)
        {
            if (peer.ContentType == "stormancer/userSession")
            {
                using (var stream = new MemoryStream(peer.UserData))
                {
                    var session = serializer.Deserialize <Session>(stream);
                    _userIdToSessionId.AddOrUpdate(session.User.Id, session.SessionId, (uid, old) => session.SessionId);
                    _sessions.AddOrUpdate(session.SessionId, Task.FromResult(session), (uid, old) => Task.FromResult(session));
                }
            }
            else
            {
                async Task <Session> getSessionAndManageDictionary(string sessionId)
                {
                    var session = await GetSessionFromAuthenticator(peer.SessionId, "");//Use default authenticator for cluster

                    if (session == null)
                    {
                        _sessions.TryRemove(sessionId, out _);
                    }
                    return(session);
                }

                _sessions.AddOrUpdate(peer.SessionId, (id) => getSessionAndManageDictionary(peer.SessionId), (id, old) => getSessionAndManageDictionary(peer.SessionId));
            }
            return(Task.CompletedTask);
        }
 public async Task ReplayTransactionLog(IScenePeerClient peer)
 {
     using (await _transactionLock.LockAsync())
     {
         await peer.RpcVoid(REPLAY_TRANSACTION_LOG_RPC, TransactionLog);
     }
 }
示例#8
0
        private string RemoveUserId(IScenePeerClient peer)
        {
            string userId;

            _peerIdToUserIdMap.TryRemove(peer.Id, out userId);
            return(userId);
        }
        public Task OnClientConnected(IScenePeerClient client)
        {
            _log.Debug("replicator", "client connected, sending object request to every connected peers");
            foreach (IScenePeerClient clt in _scene.RemotePeers)
            {
                if (client.Id != clt.Id)
                {
                    _log.Debug("replicator", "sending request to client " + clt.Id);
                    clt.RpcTask<long, List<ReplicatorDTO>>("RequestObjects", client.Id).ContinueWith(task =>
                    {
                        if (task.IsCanceled == true)
                        {
                            _log.Debug("replicator", "eeror: task cancelled");
                        }
                        if (task.IsFaulted == false)
                        {
                            var clientDtos = task.Result;
                            _log.Debug("replicator", "Object request received: " + clientDtos.Count + " from user " + clt.Id);
                            foreach (ReplicatorDTO dto in clientDtos)
                            {
                                client.Send<ReplicatorDTO>("CreateObject", dto);
                            }
                        }
                        else
                        {
                            _log.Debug("replicator", "object request failed: " + task.Exception.InnerException.Message);
                        }
                    });
                }
            }

            _log.Debug("replicator", "player connected");
            return Task.FromResult(true);
        }
        private async Task PeerConnecting(IScenePeerClient peer)
        {
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = await _sessions.GetUser(peer);

            if (user == null)
            {
                throw new ClientException("You are not authenticated.");
            }

            if (_config == null)
            {
                throw new InvalidOperationException("Game session plugin configuration missing in scene instance metadata. Please check the scene creation process.");
            }
            if (!_config.userIds.Contains(user.Id))
            {
                throw new ClientException("You are not authorized to join this game.");
            }

            var client = new Client(peer);

            if (!_clients.TryAdd(user.Id, client))
            {
                throw new ClientException("Failed to add player to the game session.");
            }

            client.Status = PlayerStatus.Connected;
            BroadcastClientUpdate(client, user.Id);
        }
        public async Task PeerDisconnecting(IScenePeerClient peer)
        {
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = await _sessions.GetUser(peer);

            if (user != null)
            {
                var client = _clients[user.Id];
                client.Peer   = null;
                client.Status = PlayerStatus.Disconnected;

                BroadcastClientUpdate(client, user.Id);
                await EvaluateGameComplete();
            }

            if (!_scene.RemotePeers.Any())
            {
                if (_gameServerProcess != null && !_gameServerProcess.HasExited)
                {
                    _logger.Log(LogLevel.Trace, "gameserver", $"Closing down game server for scene {_scene.Id}.", new { _scene.Id, Port = _port });
                    _gameServerProcess.Close();
                    _gameServerProcess = null;
                }
                _portLease?.Dispose();

                _logger.Log(LogLevel.Trace, "gameserver", $"Game server for scene {_scene.Id} shut down.", new { _scene.Id, Port = _port });
            }
        }
示例#12
0
 public Task onConnecting(IScenePeerClient client)
 {
     Player player = client.GetUserData<Player>();
     player.ID = client.Id;
     m_log.Debug("Connection", "Client (id : " + client.Id + ") with player name : \"" + player.Name + "\" connecting...");
     m_players.TryAdd(client, player);
     return Task.FromResult(true);
 }
示例#13
0
 private async Task ExecuteConnecting(IScenePeerClient client)
 {
     using (var scope = _scene.DependencyResolver.CreateChild(Constants.ApiRequestTag))
     {
         var controller = scope.Resolve <T>();
         await controller.OnConnecting(client);
     }
 }
 private Task onConnecting(IScenePeerClient client)
 {
     _scene.GetComponent<ILogger>().Debug("server", "un client tente de se connecter");
     if (_isRunning == false)
         throw new ClientException("le serveur est vérouillé.");
     else if (_players.Count >= 100)
         throw new ClientException("le serveur est complet.");
     return Task.FromResult(true);
 }
示例#15
0
        public async Task <bool> IsAuthenticated(IScenePeerClient peer)
        {
            var response = await AuthenticatorRpc(peer.SessionId, "usersession.isauthenticated", s => _serializer.Serialize(peer.SessionId, s));

            var result = _serializer.Deserialize <bool>(response.Stream);

            response.Stream.Dispose();
            return(result);
        }
        public async Task PeerDisconnecting(IScenePeerClient peer)
        {
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = await _sessions.GetUser(peer);

            Client client = null;
            string userId = null;

            if (user != null)
            {
                userId = user.Id;
                client = _clients[user.Id];
                if (userId == _config.hostUserId)
                {
                    _p2pToken = null;
                }
            }
            else
            {
                // the peer disconnected from the app and is not in the sessions anymore.
                foreach (var kvp in _clients)
                {
                    if (kvp.Value.Peer == peer)
                    {
                        userId = kvp.Key;

                        if (_config.Public)
                        {
                            _clients.TryRemove(userId, out client);
                        }
                        // no need to continue searching for the client, we already found it
                        break;
                    }
                }
            }

            if (client != null)
            {
                client.Peer   = null;
                client.Status = PlayerStatus.Disconnected;

                BroadcastClientUpdate(client, userId);
                await EvaluateGameComplete();
            }

            if (_shutdownMode == ShutdownMode.NoPlayerLeft)
            {
                if (!_clients.Values.Any(c => c.Status != PlayerStatus.Disconnected))
                {
                    CloseGameServerProcess();
                }
            }
        }
示例#17
0
        public async Task UpdateUserData <T>(IScenePeerClient peer, T data)
        {
            var response = await AuthenticatorRpc(peer.SessionId, "usersession.updateuserdata", s =>
            {
                _serializer.Serialize(peer.SessionId, s);
                _serializer.Serialize(JObject.FromObject(data), s);
            });

            response.Stream.Dispose();
        }
示例#18
0
        /// <summary>
        /// Sends a remote procedure call using raw binary data as input and output.
        /// </summary>
        /// <param name="peer">The remote peer </param>
        /// <param name="route">The target route</param>
        /// <param name="writer">A writer method writing</param>
        /// <param name="priority">The priority level used to send the request.</param>
        /// <returns>An IObservable instance that provides return values for the request.</returns>
        public static IObservable <Packet <IScenePeerClient> > Rpc(this IScenePeerClient peer, string route, Action <Stream> writer, PacketPriority priority = PacketPriority.MEDIUM_PRIORITY)
        {
            var rpcService = peer.Host.DependencyResolver.Resolve <Stormancer.Plugins.RpcService>();

            if (rpcService == null)
            {
                throw new NotSupportedException("RPC plugin not available.");
            }
            return(rpcService.Rpc(route, peer, writer, priority));
        }
示例#19
0
        private async Task PeerConnecting(IScenePeerClient peer)
        {
            if (peer.ContentType == "application/server-id")
            {
                if (IsServer(peer))
                {
                    return;
                }
                else
                {
                    throw new ClientException("Failed to authenticate as dedicated server");
                }
            }

            if (IsWorker(peer))
            {
                return;
            }
            if (peer == null)
            {
                throw new ArgumentNullException("peer");
            }
            var user = await GetUserId(peer);

            if (user == null)
            {
                throw new ClientException("You are not authenticated.");
            }

            if (_config == null)
            {
                throw new InvalidOperationException("Game session plugin configuration missing in scene instance metadata. Please check the scene creation process.");
            }
            if (!_config.userIds.Contains(user) && !_config.Public)
            {
                throw new ClientException("You are not authorized to join this game.");
            }

            var client = new Client(peer);

            if (!_clients.TryAdd(user, client))
            {
                Client alreadyConnectedClient;
                if (_clients.TryGetValue(user, out alreadyConnectedClient) && alreadyConnectedClient.Status != PlayerStatus.Disconnected && !_clients.TryUpdate(user, client, alreadyConnectedClient))
                {
                    throw new ClientException("Failed to add player to the game session.");
                }
            }

            client.Status = PlayerStatus.Connected;
            if (!_config.Public)
            {
                BroadcastClientUpdate(client, user);
            }
        }
示例#20
0
 public async Task OnDisconnected(IScenePeerClient peer)
 {
     if (_sessions.TryRemove(peer.SessionId, out var sessionAsync))
     {
         var session = await sessionAsync;
         if (session?.User?.Id != null)
         {
             _userIdToSessionId.TryRemove(session.User.Id, out _);
         }
     }
 }
 public async Task UpdateShutdownMode(ShutdownModeParameters shutdown, IScenePeerClient remotePeer)
 {
     if (remotePeer.Id == _serverPeer.Id)
     {
         if (shutdown.shutdownMode == ShutdownMode.SceneShutdown)
         {
             _shutdownMode = shutdown.shutdownMode;
             _shutdownDate = await _scene.KeepAlive(new TimeSpan(0, 0, shutdown.keepSceneAliveFor));
         }
     }
 }
        /// <summary>
        /// Starts a RPC to the provided peer.
        /// </summary>
        /// <param name="route">The remote route on which the message will be sent.</param>
        /// <param name="writer">The writer used to build the request's content.</param>
        /// <param name="priority">The priority used to send the request.</param>
        /// <param name="peer">Remote peer on which to call the procedure</param>
        /// <returns>An IObservable instance returning the RPC responses.</returns>
        public IObservable <Packet <IScenePeerClient> > Rpc(string route, IScenePeerClient peer, Action <Stream> writer, PacketPriority priority)
        {
            return(Observable.Create <Packet <IScenePeerClient> >(
                       observer =>
            {
                var rr = peer.Routes.FirstOrDefault(r => r.Name == route);
                if (rr == null)
                {
                    throw new ArgumentException("The target route does not exist on the remote host.");
                }
                //string version;
                //if (!rr.Metadata.TryGetValue(RpcHostPlugin.PluginName, out version) || version != RpcHostPlugin.Version)
                //{
                //    throw new InvalidOperationException("The target remote route does not support the plugin RPC version " + RpcHostPlugin.Version);
                //}

                var rq = new Request <IScenePeerClient> {
                    Observer = observer
                };
                var id = this.ReserveId();
                if (_pendingRequests.TryAdd(id, rq))
                {
                    _scene.Send(new MatchPeerFilter(peer), route, s =>
                    {
                        s.Write(BitConverter.GetBytes(id), 0, 2);
                        writer(s);
                    }, priority, PacketReliability.RELIABLE_ORDERED);
                }

                var cancellationToken = GetCancellationTokenForPeer(peer);

                var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                linkedCts.Token.Register(() =>
                {
                    observer.OnError(new PeerDisconnectedException("Peer disconnecter from the scene."));
                });


                return () =>
                {
                    linkedCts.Dispose();
                    Request <IScenePeerClient> _;
                    if (!rq.HasCompleted && _pendingRequests.TryRemove(id, out _))
                    {
                        _scene.Send(new MatchPeerFilter(peer), RpcHostPlugin.CancellationRouteName, s =>
                        {
                            s.Write(BitConverter.GetBytes(id), 0, 2);
                        }, priority, PacketReliability.RELIABLE_ORDERED);
                    }
                };
            }));
        }
示例#23
0
    Task OnConnected(IScenePeerClient client)
    {
        List <ChatMessageDTO> messages = _MessagesCache.ToList();
        int i = messages.Count - 1;

        while (i >= 0)
        {
            client.Send <ChatMessageDTO>("chat", messages[i]);
            i--;
        }
        return(Task.FromResult(true));
    }
示例#24
0
        /// <summary>
        /// Sends a RPC to an host.
        /// </summary>
        /// <typeparam name="TData">The type of data to send.</typeparam>
        /// <typeparam name="TResult">The type of the data returned by the request.</typeparam>
        /// <param name="peer">The peer to send the request to.</param>
        /// <param name="route">The target route.</param>
        /// <param name="parameter">The request parameter.</param>
        /// <param name="priority">The request's priority level.</param>
        /// <returns>An observable to subscribe to to get responses from the peer.</returns>
        public static IObservable <TResult> SendRequest <TData, TResult>(this IScenePeerClient peer, string route, TData parameter, PacketPriority priority = PacketPriority.MEDIUM_PRIORITY)
        {
            return(peer.Rpc(route, s =>
            {
                peer.Serializer().Serialize(parameter, s);
            }, priority).Select(packet =>
            {
                var value = packet.Serializer().Deserialize <TResult>(packet.Stream);

                return value;
            }));
        }
示例#25
0
        public Task <GameServerStartupParameters> SetReady(string id, IScenePeerClient client)
        {
            if (_startingServers.TryRemove(id, out var server))
            {
                server.Peer   = client;
                server.RunTcs = new TaskCompletionSource <GameServerStartupParameters>();
                _readyServers.TryAdd(id, server);
                return(server.RunTcs.Task);
            }

            throw new ClientException($"dedicatedServer.notInPool");
        }
    Task OnConnected(IScenePeerClient client)
    {
        List<ChatMessageDTO> messages = _MessagesCache.ToList();
        int i = messages.Count - 1;

        while (i >= 0)
        {
            client.Send<ChatMessageDTO>("chat", messages[i]);
            i--;
        }
        return Task.FromResult(true);
    }
        private async Task SubmitTransaction(TransactionCommand cmd)
        {
            using (await _transactionLock.LockAsync())
            {
                _logger.Log(LogLevel.Debug, "gameSession", "Transaction submitted.", new
                {
                    map     = PlayerMap,
                    players = _players.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Id),
                    Cmd     = cmd
                });
                var responses = await Task.WhenAll(PlayerMap.Select(async p =>
                {
                    IScenePeerClient peer = null;
                    _players.TryGetValue(p.Value, out peer);

                    TransactionResponse response = null;
                    if (peer != null)
                    {
                        try
                        {
                            var r     = await peer.RpcTask <TransactionCommand, TransactionResponse>(VALIDATE_TRANSACTION_RPC, cmd);
                            r.Success = true;
                            response  = r;
                        }
                        catch (Exception)//Failed to execute transaction update on client
                        {
                            response = new TransactionResponse {
                                Success = false
                            };
                        }
                    }
                    return(Tuple.Create(p.Key, response));
                }));

                var receivedResponses = responses.Where(t => t.Item2 != null);

                var isValid = true;
                if (receivedResponses.Any())
                {
                    isValid = receivedResponses.All(t => t.Item2.Success) && receivedResponses.Select(t => t.Item2).Distinct().Count() == 1;
                }

                if (!isValid)
                {
                    await EnsureTransactionFailed($"game states hash comparaison failed: [{string.Join(", ", responses.Select(t => $"'{t.Item1}' => {t.Item2}"))}]");
                }
                var hash = responses.FirstOrDefault(r => r.Item2 != null)?.Item2.Hash;
                _commands.Add(new TransactionLogItem {
                    Command = cmd, ResultHash = hash ?? 0, HashAvailable = hash.HasValue
                });
            }
        }
示例#28
0
        internal Task <GameServerStartupParameters> SetReady(string onlineId, IScenePeerClient peer)
        {
            var poolId = onlineId.Split('/')[0];
            var id     = onlineId.Split('/')[1];
            var pool   = GetPool(poolId);

            if (pool == null)
            {
                throw new ArgumentException($"pool {poolId} not found");
            }
            _sessionToOnlineId.TryAdd(peer.SessionId, onlineId);
            return(pool.SetReady(id, peer));
        }
 private Task onConnecting(IScenePeerClient client)
 {
     _scene.GetComponent <ILogger>().Debug("server", "un client tente de se connecter");
     if (_isRunning == false)
     {
         throw new ClientException("le serveur est vérouillé.");
     }
     else if (_players.Count >= 100)
     {
         throw new ClientException("le serveur est complet.");
     }
     return(Task.FromResult(true));
 }
 public bool IsServer(IScenePeerClient peer)
 {
     if (peer != null && peer.ContentType == "application/server-id")
     {
         var peerGuid   = new Guid(peer.UserData);
         var serverGuid = new Guid(_serverGuid);
         return(serverGuid == peerGuid);
     }
     else
     {
         return(false);
     }
 }
        private async Task OnConnected(IScenePeerClient client)
        {
            _logger.Log(LogLevel.Debug, "gameSession", "client connected", new { });
            var user = await _sessions.GetUser(client);

            if (user == null)
            {
                throw new InvalidOperationException("The client must be authenticated");
            }

            _players[user.Id] = client;

            await ReplayTransactionLog(client);
        }
示例#32
0
        public async Task UpdateUserData <T>(IScenePeerClient peer, T data)
        {
            var user = await GetUser(peer);

            if (user == null)
            {
                throw new InvalidOperationException("User not found.");
            }
            else
            {
                user.UserData = Newtonsoft.Json.Linq.JObject.FromObject(data);
                await _userService.UpdateUserData(user.Id, data);
            }
        }
示例#33
0
        public async Task OnMessageReceived(IScenePeerClient client, string text, Action <ChatMessageDto, DestinationType> sender)
        {
            // Check if user is connected
            ChatUserInfoDto userInfo = null;

            _connectedUsers.TryGetValue(client, out userInfo);
            if (userInfo == null)
            {
                throw new ClientException($"User not found {client.Id} .");
            }

            // Store message in log
            ChatMessage messageLog = new ChatMessage
            {
                Channel  = client.SceneId,
                Date     = DateTime.UtcNow,
                Message  = text,
                Metadata = new JObject(),
                UserInfo = new UserInfo
                {
                    UserId = userInfo.UserId,
                    Data   = JObject.Parse(userInfo.Data)
                }
            };

            ChatMessageDto messageDto = new ChatMessageDto
            {
                Message   = text,
                TimeStamp = _env.Clock,
                UserInfo  = userInfo,
            };

            ChatMsgReceivedContext receiveCtx = new ChatMsgReceivedContext(messageLog, messageDto);

            receiveCtx.Destination = DestinationType.All;

            await _chatEventHandler?.RunEventHandler(eh =>
            {
                return(eh.OnMessageReceived(receiveCtx));
            }, ex =>
            {
                _log.Log(LogLevel.Error, _logCategory, "An error occured when the chat service check if the user is in jail.", ex);
                throw new ClientException($"An error occured when the chat service check if the user is in jail.");
            });

            _chatRepository.AddMessageLog(receiveCtx.Message);
            _messagesSource.OnNext(receiveCtx.Message);
            sender(receiveCtx.MessageDto, receiveCtx.Destination);
        }
        public async Task <Dictionary <string, string> > GetStatus(IScenePeerClient peer)
        {
            var session = await _sessions.GetSession(peer);

            var result = new Dictionary <string, string>(session.Authentications.ToDictionary(entry => entry.Key, entry => entry.Value));
            var tasks  = new List <Task>();

            foreach (var provider in _authProviders)
            {
                tasks.Add(provider.OnGetStatus(result, session));
            }
            await Task.WhenAll(tasks);

            return(result);
        }
示例#35
0
        public Task onConnecting(IScenePeerClient client)
        {
            Player player = client.GetUserData<Player>();

            if (m_game != null && m_nbPlayer == m_game.MaxPlayer)
                throw new ClientException("Game if full.");
            if (m_started == true)
                throw new ClientException("Game is on its way");
            player.ID = client.Id;
            m_players[client] = player;
            if (m_game != null)
                m_game.IDPlayers[client.Id] = player;
            m_log.Debug("Connection", "Client (id : " + client.Id + ") with player name : \"" + m_players[client].Name + "\" connected to game.");
            return Task.FromResult(true);
        }
示例#36
0
        private Task ToggleClientLogs(IScenePeerClient client, bool shouldEnable)
        {
            string previousStateString;
            var    previousState = client.Metadata.TryGetValue(ClientLogsPluginConstants.isLoggingMetadataKey, out previousStateString) ? previousStateString == "True" : false;

            if (previousState != shouldEnable)
            {
                client.Metadata[ClientLogsPluginConstants.isLoggingMetadataKey] = shouldEnable.ToString();
                return(client.SendVoidRequest(ClientLogsPluginConstants.EnableClientLogsRoute, shouldEnable));
            }
            else
            {
                return(Task.FromResult(System.Reactive.Unit.Default));
            }
        }
示例#37
0
 public Task onConnected(IScenePeerClient client)
 {
     m_log.Debug("Connection", "Client (id : " + client.Id + ") with player name : \"" + m_players[client].Name + "\" connected");
     client.Send("GetIdPlayer", client.Id);
     return Task.FromResult(true);
 }
示例#38
0
 // On connected is called by the connected event.
 // We can use this function to read to data sent by the player and store them.
 // please note that it receives the same data onConnect() so we can store infos here while only validating them on the connecting event
 //
 private Task OnConnected(IScenePeerClient client)
 {
     _playersConnected++;
     return Task.FromResult(true);
 }
示例#39
0
        private async Task OnConnected(IScenePeerClient client)
        {
            var pInfos = PlayerInfos.FromPeer(client);

            var player = new Player(pInfos, client.Id);

            _players.AddOrUpdate(client.Id, player, (id, old) => player);

            Ship ship = null;
            if (!player.IsObserver)
            {
                ship = CreateShip(player);
                player.ShipId = ship.id;
                _ships.AddOrUpdate(ship.id, ship, (id, old) => ship);

                var dto = new ShipCreatedDto { timestamp = _scene.GetComponent<IEnvironment>().Clock, id = ship.id, team = ship.team, x = ship.x, y = ship.y, rot = ship.rot, weapons = ship.weapons, status = ship.Status };
                var data = new[] { dto };

                client.Send("ship.me", s => client.Serializer().Serialize(data, s), PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE);

                _scene.Broadcast("ship.add", data, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE);

            }

            // Send ships to new client
            var shipsToSend = new List<ShipCreatedDto>();
            foreach (var s in _ships.Values.ToArray())
            {
                var dto = new ShipCreatedDto { timestamp = _scene.GetComponent<IEnvironment>().Clock, id = s.id, team = s.team, x = s.x, y = s.y, rot = s.rot, weapons = s.weapons, status = s.Status };
                if (ship == null || ship.id != s.id)
                {
                    shipsToSend.Add(dto);
                }
            }
            client.Send("ship.add", stream =>
            {
                client.Serializer().Serialize(shipsToSend, stream);
            }, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE);

            if (ship != null)
            {
                await Task.Delay(1000);
                ship.UpdateStatus(ShipStatus.InGame);
            }

            _scene.GetComponent<ILogger>().Info("gameScene", "Added ship");

            StartUpdateLoop();
        }
示例#40
0
 internal static PlayerInfos FromPeer(IScenePeerClient peer)
 {
     return peer.GetUserData<PlayerInfos>();
   //  return peer.Serializer().Deserialize<PlayerInfos>(new MemoryStream(peer.UserData));
 }
示例#41
0
 // onConnecting is called by the connecting event.
 // We use this function to prevent unwanted clients to connect to the scene.
 // In our case we want players to use the correct version and don't want more than 100 of them connected at the same time
 // This function could also be used to check the incomming client connection datas such as nicknames, etc...
 //
 private Task OnConnecting(IScenePeerClient client)
 {
     _log.Debug("main", "A new client try to connect");
     var player_dto = client.GetUserData<ConnectionDtO>();
     if (_isRunning == false)
     {
         throw new ClientException("le serveur est vérouillé.");
     }
     else if (_playersConnected >= 100)
     {
         throw new ClientException("le serveur est complet.");
     }
     else if (player_dto.version != _version)
     {
         throw new ClientException("mauvaise version");
     }
     return Task.FromResult(true);
 }
  private void sendConnectedPlayersToNewPeer(IScenePeerClient client)
  {
      client.Send("player_connected", s =>
      {
          var writer = new BinaryWriter(s, Encoding.UTF8, true);
          foreach (Player p in _players.Values)
          {
              writer.Write(p.id);
              if (p.status == StatusTypes.ALIVE)
                  writer.Write(0);
              else
                  writer.Write(1);
              writer.Write(p.color_red);
              writer.Write(p.color_blue);
              writer.Write(p.color_green);
          }
      }, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE);
 }
        private Task onConnected(IScenePeerClient client)
        {
            myGameObject player = client.GetUserData<myGameObject>();
            if (_players.Count < 100)
            {
                _scene.Broadcast("chat", player.name + " a rejoint le combat !");
                _scene.GetComponent<ILogger>().Debug("server", "client connected with name : " + player.name);
                client.Send("get_id", s =>
                {
                    var writer = new BinaryWriter(s, Encoding.UTF8, true);
                    writer.Write(client.Id);
                }, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE);
                player.id = client.Id;
                sendConnectedPlayersToNewPeer(client);
                sendConnexionNotification(player);
                _players.TryAdd(client.Id, new Player(player, _env.Clock));

            }
            return Task.FromResult(true);
        }