コード例 #1
0
ファイル: BaseLobby.cs プロジェクト: jraicr/MST
        /// <summary>
        /// Set the lobby property
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetProperty(string key, string value)
        {
            propertiesList.Set(key, value);

            OnLobbyPropertyChange(key);
            return(true);
        }
コード例 #2
0
ファイル: BaseLobby.cs プロジェクト: jraicr/MST
        protected virtual MstProperties GenerateOptions()
        {
            var options = new MstProperties();

            options.Set(Mst.Args.Names.LobbyId, Id.ToString());

            return(options);
        }
コード例 #3
0
        /// <summary>
        /// Set's current player's properties
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="callback"></param>
        public void SetMyProperty(string key, string value, SuccessCallback callback)
        {
            var data = new MstProperties();

            data.Set(key, value);

            Mst.Client.Lobbies.SetMyProperties(data, callback, _connection);
        }
コード例 #4
0
        /// <summary>
        /// Create options from dictionary
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static MstProperties FromDictionary(IDictionary dictionary)
        {
            var properties = new MstProperties();

            foreach (var key in dictionary.Keys)
            {
                properties.Set(key.ToString(), dictionary[key].ToString());
            }

            return(properties);
        }
コード例 #5
0
ファイル: ClientsSpawnRequestPacket.cs プロジェクト: poup/MST
        public override string ToString()
        {
            var options = new MstProperties(Options);

            if (options.IsValueEmpty(MstDictKeys.ROOM_REGION))
            {
                options.Set(MstDictKeys.ROOM_REGION, "International");
            }

            return(options.ToReadableString() + " " + CustomOptions.ToReadableString());
        }
コード例 #6
0
        /// <summary>
        /// Sends a request to master server, to spawn a process in a given region, and with given options
        /// </summary>
        /// <param name="options"></param>
        /// <param name="customOptions"></param>
        /// <param name="region"></param>
        /// <param name="callback"></param>
        public void RequestSpawn(MstProperties options, MstProperties customOptions, string region, SpawnRequestResultHandler callback, IClientSocket connection)
        {
            // If we are not connected
            if (!connection.IsConnected)
            {
                callback?.Invoke(null, "Not connected");
                return;
            }

            // Set region to room by filter. If region is empty the room will be international
            options.Set(MstDictKeys.roomRegion, string.IsNullOrEmpty(region) ? string.Empty : region);

            // Create spawn request message packet
            var data = new ClientsSpawnRequestPacket()
            {
                // Options for spawners module
                Options = options,

                // Options that will be send to room
                CustomOptions = customOptions
            };

            // Send request to Master Server SpawnerModule
            connection.SendMessage((short)MstMessageCodes.ClientsSpawnRequest, data, (status, response) =>
            {
                // If spawn request failed
                if (status != ResponseStatus.Success)
                {
                    Logs.Error($"An error occurred when spawn request [{response.AsString()}]");
                    callback?.Invoke(null, response.AsString());
                    return;
                }

                // Create new spawn request controller
                var controller = new SpawnRequestController(response.AsInt(), connection, options);

                // List controler by spawn task id
                _localSpawnRequests[controller.SpawnTaskId] = controller;

                Logs.Debug($"Room was successfuly started with client options: {data.Options.ToReadableString()}, {data.CustomOptions.ToReadableString()}");

                callback?.Invoke(controller, null);
            });
        }
コード例 #7
0
        /// <summary>
        /// Sends a request to create a lobby, using a specified factory
        /// </summary>
        public void CreateLobby(string factory, MstProperties options, CreateLobbyCallback calback, IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                calback.Invoke(null, "Not connected");
                return;
            }

            options.Set(MstDictKeys.lobbyFactoryId, factory);

            connection.SendMessage((short)MstMessageCodes.CreateLobby, options.ToBytes(), (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    calback.Invoke(null, response.AsString("Unknown error"));
                    return;
                }

                var lobbyId = response.AsInt();

                calback.Invoke(lobbyId, null);
            });
        }
コード例 #8
0
ファイル: SpawnerController.cs プロジェクト: jraicr/MST
        /// <summary>
        /// Default spawn spawned process request handler that will be used by controller if <see cref="spawnRequestHandler"/> is not overriden
        /// </summary>
        /// <param name="data"></param>
        /// <param name="message"></param>
        public virtual void SpawnRequestHandler(SpawnRequestPacket data, IIncomingMessage message)
        {
            Logger.Debug($"Default spawn handler started handling a request to spawn process for spawn controller [{SpawnerId}]");

            /************************************************************************/
            // Create process args string
            var processArguments = new MstProperties();

            /************************************************************************/
            // Check if we're overriding an IP to master server
            var masterIpArgument = string.IsNullOrEmpty(SpawnSettings.MasterIp) ?
                                   Connection.ConnectionIp : SpawnSettings.MasterIp;

            // Create master IP arg
            processArguments.Set(Mst.Args.Names.MasterIp, masterIpArgument);

            /************************************************************************/
            /// Check if we're overriding a port to master server
            var masterPortArgument = SpawnSettings.MasterPort < 0 ? Connection.ConnectionPort : SpawnSettings.MasterPort;

            // Create master port arg
            processArguments.Set(Mst.Args.Names.MasterPort, masterPortArgument);

            /************************************************************************/
            // Machine Ip
            processArguments.Set(Mst.Args.Names.RoomIp, SpawnSettings.MachineIp);

            /************************************************************************/
            // Create port for room arg
            int machinePortArgument = Mst.Server.Spawners.GetAvailablePort();

            processArguments.Set(Mst.Args.Names.RoomPort, machinePortArgument);

            /************************************************************************/
            // Room Name
            //processArguments.Set(Mst.Args.Names.RoomName, $"\"{data.Options.AsString(MstDictKeys.roomName, "Room_" + Mst.Helper.CreateRandomString(6))}\"");

            /************************************************************************/
            // Room Region
            //processArguments.Set(Mst.Args.Names.RoomRegion, $"\"{SpawnSettings.Region}\"");

            /************************************************************************/
            // Room Max Connections
            //if (data.Options.Has(MstDictKeys.maxPlayers))
            //{
            //    processArguments.Set(Mst.Args.Names.RoomMaxConnections, data.Options.AsString(MstDictKeys.maxPlayers));
            //}

            /************************************************************************/
            // Get the scene name
            //if (data.Options.Has(MstDictKeys.sceneName))
            //{
            //    processArguments.Set(Mst.Args.Names.LoadScene, data.Options.AsString(MstDictKeys.sceneName));
            //}

            /************************************************************************/
            // Create use websockets arg
            //if (SpawnSettings.UseWebSockets)
            //{
            //    processArguments.Set(Mst.Args.Names.UseWebSockets, string.Empty);
            //}

            /************************************************************************/
            // Create spawn id arg
            processArguments.Set(Mst.Args.Names.SpawnTaskId, data.SpawnTaskId);

            /************************************************************************/
            // Create spawn code arg
            processArguments.Set(Mst.Args.Names.SpawnTaskUniqueCode, data.SpawnTaskUniqueCode);

            /************************************************************************/
            // Create custom args
            processArguments.Append(data.CustomOptions);

            /************************************************************************/
            // Path to executable
            var executablePath = SpawnSettings.ExecutablePath;

            if (string.IsNullOrEmpty(executablePath))
            {
                executablePath = File.Exists(Environment.GetCommandLineArgs()[0])
                    ? Environment.GetCommandLineArgs()[0]
                    : Process.GetCurrentProcess().MainModule.FileName;
            }

            // In case a path is provided with the request
            if (data.Options.Has(MstDictKeys.ROOM_EXE_PATH))
            {
                executablePath = data.Options.AsString(MstDictKeys.ROOM_EXE_PATH);
            }

            if (!string.IsNullOrEmpty(data.OverrideExePath))
            {
                executablePath = data.OverrideExePath;
            }

            /// Create info about starting process
            var startProcessInfo = new ProcessStartInfo(executablePath)
            {
                CreateNoWindow  = false,
                UseShellExecute = true,
                Arguments       = processArguments.ToReadableString(" ", " ")
            };

            Logger.Debug("Starting process with args: " + startProcessInfo.Arguments);

            var processStarted = false;

            try
            {
                new Thread(() =>
                {
                    try
                    {
                        using (var process = Process.Start(startProcessInfo))
                        {
                            Logger.Debug("Process started. Spawn Id: " + data.SpawnTaskId + ", pid: " + process.Id);
                            processStarted = true;

                            lock (processLock)
                            {
                                // Save the process
                                processes[data.SpawnTaskId] = process;
                            }

                            var processId = process.Id;

                            // Notify server that we've successfully handled the request
                            MstTimer.RunInMainThread(() =>
                            {
                                message.Respond(ResponseStatus.Success);
                                NotifyProcessStarted(data.SpawnTaskId, processId, startProcessInfo.Arguments);
                            });

                            process.WaitForExit();
                        }
                    }
                    catch (Exception e)
                    {
                        if (!processStarted)
                        {
                            MstTimer.RunInMainThread(() => { message.Respond(ResponseStatus.Failed); });
                        }

                        Logger.Error("An exception was thrown while starting a process. Make sure that you have set a correct build path. " +
                                     $"We've tried to start a process at [{executablePath}]. You can change it at 'SpawnerBehaviour' component");
                        Logger.Error(e);
                    }
                    finally
                    {
                        lock (processLock)
                        {
                            // Remove the process
                            processes.Remove(data.SpawnTaskId);
                        }

                        MstTimer.RunInMainThread(() =>
                        {
                            // Release the port number
                            Mst.Server.Spawners.ReleasePort(machinePortArgument);
                            Logger.Debug($"Notifying about killed process with spawn id [{data.SpawnTaskId}]");
                            NotifyProcessKilled(data.SpawnTaskId);
                        });
                    }
                }).Start();
            }
            catch (Exception e)
            {
                message.Respond(e.Message, ResponseStatus.Error);
                Logs.Error(e);
            }
        }