示例#1
0
    // Start is called before the first frame update
    void Start()
    {
        NetworkingManager.Singleton.NetworkConfig.ConnectionApproval = true;
        NetworkingManager.Singleton.OnServerStarted            += OnServerStarted;
        NetworkingManager.Singleton.OnClientConnectedCallback  += OnClientConnected;
        NetworkingManager.Singleton.OnClientDisconnectCallback += OnClientDisconnect;
        NetworkingManager.Singleton.ConnectionApprovalCallback += OnConnectionApproved;

#if UNITY_EDITOR
#else
        if (Application.isBatchMode)
        {
            string activeSceneName = SceneManager.GetActiveScene().name;
            if (activeSceneName == "Map001")
            {
                //Connect to server from Client
                NetworkingManager.Singleton.GetComponent <UnetTransport>().ConnectAddress   = "0.0.0.0";
                NetworkingManager.Singleton.GetComponent <UnetTransport>().ServerListenPort = 7777;

                const int port = 7777;
                LogModule.WriteToLogFile("[ServerModule] Server Module Start at Port :7777 ");

                // Only run on Server mode
                if (LocalTest)
                {
                    NetworkingManager.Singleton.StartServer();
                }
                else
                {
                    if (GameLift.GameLiftStart(port))
                    {
                        NetworkingManager.Singleton.StartServer();
                    }
                }
            }
            else if (activeSceneName == "Map002")
            {
                //Connect to server from Client
                NetworkingManager.Singleton.GetComponent <UnetTransport>().ConnectAddress   = "0.0.0.0";
                NetworkingManager.Singleton.GetComponent <UnetTransport>().ServerListenPort = 8888;

                const int port = 8888;
                LogModule.WriteToLogFile("[ServerModule] Server Module Start at Port :8888 ");

                // Only run on Server mode
                if (LocalTest)
                {
                    NetworkingManager.Singleton.StartServer();
                }
                else
                {
                    if (GameLift.GameLiftStart(port))
                    {
                        NetworkingManager.Singleton.StartServer();
                    }
                }
            }
        }
#endif
    }
示例#2
0
    IEnumerator MatchStatusPolling()
    {
        LogModule.WriteToLogFile("[ClientModule] Send Polling with TicketId - " + this.ClientConnection.TicketId);
        yield return(new WaitForSeconds(5.0f));

        StartCoroutine(HttpModule.PutRequest(ApiModule.GetMatchStatusAPI(),
                                             new APIModule.MatchstatusRequest(this.PlayerId, this.ClientConnection.TicketId), MatchStatusCallback));
    }
示例#3
0
    private void MatchRequestCallback(string matchmakingResponse)
    {
        LogModule.WriteToLogFile("[ClientModule] Match Request Callback - " + matchmakingResponse);
        APIModule.MatchmakingResponse matchmakingResult = JsonUtility.FromJson <APIModule.MatchmakingResponse>(matchmakingResponse);
        this.ClientConnection.TicketId = matchmakingResult.ticketId;

        StartCoroutine(MatchStatusPolling());
    }
示例#4
0
 public void DisconnectToServer()
 {
     if (NetworkingManager.Singleton.IsConnectedClient)
     {
         LogModule.WriteToLogFile("[ClientModule] Disconnect CLient");
         NetworkingManager.Singleton.StopClient();
     }
 }
示例#5
0
 private void OnClientConnected(ulong clientId)
 {
     //Called when Client connected
     if (IsServer)
     {
         LogModule.WriteToLogFile("[ServerModule] On Client Connected - " + clientId);
     }
 }
示例#6
0
    public bool GameLiftStart(int listenPort)
    {
        //Debug.Log("GameLift Start with Port:" + listenPort);
        LogModule.WriteToLogFile("[GameLift] GameLift Start with Port:" + listenPort);
        var initSDKOutcome = GameLiftServerAPI.InitSDK();

        if (initSDKOutcome.Success)
        {
            ProcessParameters processParameters = new ProcessParameters(
                (gameSession) =>
            {
                //OnStartGameSession Callback
                LogModule.WriteToLogFile("[GameLift] OnStartGameSession with Parameter=" + gameSession);
                GameLiftServerAPI.ActivateGameSession();
            },
                (gameSession) =>
            {
                //OnUpdateGameSession Callback
                //You can implement custom Match update logics using Backfill Ticket, UpdateReason, GameSession data.
                LogModule.WriteToLogFile("[GameLift] OnUpdateGameSession with Backfill Ticket=" + gameSession.BackfillTicketId + ", UpdateReason=" + gameSession.UpdateReason);
            },
                () =>
            {
                //OnProcessTerminate Callback
                LogModule.WriteToLogFile("[GameLift] ProcessEnding");
                GameLiftServerAPI.ProcessEnding();
            },
                () =>
            {
                //OnHealthCheck Callback
                return(true);
            },
                listenPort,
                new LogParameters(new List <string>()
            {
                "./local/game/logs/myserver.log"
                //"C:\\game\\myserver.log"
            }
                                  ));
            var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters);
            if (processReadyOutcome.Success)
            {
                LogModule.WriteToLogFile("[GameLift] ProcessReady Success");
                return(true);
            }
            else
            {
                LogModule.WriteToLogFile("[GameLift] ProcessReady Failure : " + processReadyOutcome.Error.ToString());
                return(false);
            }
        }
        else
        {
            LogModule.WriteToLogFile("[GameLift] InitSDK failure : " + initSDKOutcome.Error.ToString());
            return(false);
        }
    }
示例#7
0
    private IEnumerator CloseServerRoutine()
    {
        yield return(new WaitForSeconds(10.0f));

        LogModule.WriteToLogFile("[ServerModule] Server will soon restart");
#if UNITY_EDITOR
#else
        Application.Quit();
#endif
    }
示例#8
0
 public void ConnectToServer()
 {
     LogModule.WriteToLogFile("[ClientModule] Connect To Server. IP=" + ClientConnection.Addess + ", Port=" + ClientConnection.Port);
     NetworkingManager.Singleton.GetComponent <UnetTransport>().ConnectAddress = ClientConnection.Addess;
     NetworkingManager.Singleton.GetComponent <UnetTransport>().ConnectPort    = ClientConnection.Port;
     NetworkingManager.Singleton.NetworkConfig.ConnectionApproval = true;
     NetworkingManager.Singleton.NetworkConfig.ConnectionData     = System.Text.Encoding.UTF8.GetBytes(this.ClientConnection.PlayerSessionId);
     LogModule.WriteToLogFile("[ClientModule] ConnectionData=" + NetworkingManager.Singleton.NetworkConfig.ConnectionData);
     NetworkingManager.Singleton.StartClient();
 }
示例#9
0
    public APIModule()
    {
        Dictionary <string, string> arguments = GetCommandLineArguments();

        if (arguments.ContainsKey("url"))
        {
            API_URL = arguments["url"];
        }
        LogModule.WriteToLogFile("[APIModule] Given API URL : " + API_URL);
    }
示例#10
0
    public void OnApplicationQuit()
    {
        LogModule.WriteToLogFile("[ServerModule] On Application Quit");
#if UNITY_EDITOR
#else
        if (Application.isBatchMode && !LocalTest)
        {
            GameLift.EndProcess();
        }
#endif
    }
示例#11
0
 private void OnServerStarted()
 {
     //This runs at Server side
     LogModule.WriteToLogFile("[ServerModule] On Server Started");
     if (IsServer)
     {
         StartCoroutine(SpawnFood());
         if (SceneManager.GetActiveScene().name == "Map002")
         {
             StartCoroutine(SpawnBoss());
         }
     }
 }
示例#12
0
    public void EndProcess()
    {
        var processEndingOutcome = GameLiftServerAPI.ProcessEnding();

        if (processEndingOutcome.Success)
        {
            LogModule.WriteToLogFile("[GameLift] End GameLift Server Process");
        }
        else
        {
            LogModule.WriteToLogFile("[GameLift] Process Ending Failed. Result : " + processEndingOutcome.Error.ToString());
        }
    }
示例#13
0
    public void RemovePlayer(string playerSessionId)
    {
        var removePlayerSessionOutcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId);

        if (removePlayerSessionOutcome.Success)
        {
            LogModule.WriteToLogFile("[GameLift] Remove Player Session Success : " + playerSessionId);
        }
        else
        {
            LogModule.WriteToLogFile("[GameLift] Remove Player Session Failed. Result : " + removePlayerSessionOutcome.Error.ToString());
        }
    }
示例#14
0
    public void OnClickSignUpBtn()
    {
        string inputName     = NameInputField.text;
        string inputPassword = PasswordInputField.text;

        if (ClientModule.Singleton.SignUp(inputName, inputPassword))
        {
            LogModule.WriteToLogFile("[ClientModule] Sign Up Succeeded!");
        }
        else
        {
            LogModule.WriteToLogFile("[ClientModule] Sign Up Failed. inputName-" + inputName + ", inputPassword-" + inputPassword);
        }
    }
示例#15
0
    public bool AcceptPlayer(string playerSessionId)
    {
        var acceptPlayerSessionOutcome = GameLiftServerAPI.AcceptPlayerSession(playerSessionId);

        if (acceptPlayerSessionOutcome.Success)
        {
            LogModule.WriteToLogFile("[GameLift] Player Session Validated");
            return(true);
        }
        else
        {
            LogModule.WriteToLogFile("[GameLift] Player Session Rejected. AcceptPlayerSession Result : " + acceptPlayerSessionOutcome.Error.ToString());
            return(false);
        }
    }
示例#16
0
 private void PlayerCommand()
 {
     if (Input.GetKeyDown(KeyCode.Space))
     {
         LogModule.WriteToLogFile("Space Enter");
         string activeSceneName = SceneManager.GetActiveScene().name;
         ClientModule.Singleton.PlayerStatus = ClientModule.PlayStatus.MOVE;
         if (activeSceneName == "Map001")
         {
             ClientModule.Singleton.MoveToWorld("Map002");
         }
         else if (activeSceneName == "Map002")
         {
             ClientModule.Singleton.MoveToWorld("Map001");
         }
     }
 }
示例#17
0
    private void OnConnectionApproved(byte[] connectionData, ulong clientId, MLAPI.NetworkingManager.ConnectionApprovedDelegate callback)
    {
        LogModule.WriteToLogFile("[ServerModule] On Connection Approved");

        string connectionString = System.Text.Encoding.UTF8.GetString(connectionData);

        LogModule.WriteToLogFile("[ServerModule] Connection String - " + connectionString);

        string playerSessionId = connectionString;

        //If approve is true, the connection will be added. If it is false, the client gets disconnected
        bool approve = !string.IsNullOrEmpty(connectionString);

        if (!LocalTest)
        {
            if (!approve || !GameLift.AcceptPlayer(playerSessionId))
            {
                LogModule.WriteToLogFile("[ServerModule] Disconnect Client from server - clientId : " + clientId + ", playerSessionId : " + playerSessionId);
                approve = false;
            }
            else
            {
                approve = true;
            }
        }
        bool createPlayerObject = approve;

        float z = 0;
        float x = Random.Range
                      (Camera.main.ScreenToWorldPoint(new Vector3(0, 0, z)).x, Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, z)).x);
        float y = Random.Range
                      (Camera.main.ScreenToWorldPoint(new Vector3(0, 0, z)).y, Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height, z)).y);
        Vector3 randomPos = new Vector3(x, y, z);

        Vector3 spawnPosition = randomPos;

        if (approve)
        {
            LogModule.WriteToLogFile("[ServerModule] Spawn Position from Server - " + spawnPosition);
            PlayerSessionMap["" + clientId] = playerSessionId;
        }

        callback(createPlayerObject, null, approve, spawnPosition, null);
    }
示例#18
0
    public static IEnumerator PutRequest(string url, object body, Action <string> callback)
    {
        var json = JsonUtility.ToJson(body);

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json);

        using (UnityWebRequest webRequest = UnityWebRequest.Put(url, bytes))
        {
            yield return(webRequest.SendWebRequest());

            if (webRequest.isNetworkError)
            {
                LogModule.WriteToLogFile("[HttpModule] " + webRequest.error);
            }
            else
            {
                LogModule.WriteToLogFile("[HttpModule] " + webRequest.downloadHandler.text);
                callback(webRequest.downloadHandler.text);
            }
        }
    }
示例#19
0
    public void OnClickSignInBtn()
    {
        string inputName     = NameInputField.text;
        string inputPassword = PasswordInputField.text;

        LogModule.WriteToLogFile("[ClientModule] Onclick - " + ClientModule.Singleton);
        if (ConnectionStatus != null)
        {
            ConnectionStatus.text = "Entering the world";
        }

        if (ClientModule.Singleton.SignIn(inputName, inputPassword))
        {
            // Login existing server
            ClientModule.Singleton.SignInProcess(inputName);
        }
        else
        {
            LogModule.WriteToLogFile("[ClientModule] Sign In Failed. inputName-" + inputName + ", inputPassword-" + inputPassword);
        }
    }
示例#20
0
    private void MatchStatusCallback(string matchstatusResponse)
    {
        LogModule.WriteToLogFile("[ClientModule] MatchStatus Callback : " + matchstatusResponse);
        APIModule.MatchstatusResponse matchstatusResult = JsonUtility.FromJson <APIModule.MatchstatusResponse>(matchstatusResponse);

        if (!LocalTest)
        {
            if (matchstatusResult.port > 0)
            {
                this.ClientConnection.MatchSuccess    = true;
                this.ClientConnection.Addess          = matchstatusResult.address;
                this.ClientConnection.Port            = matchstatusResult.port;
                this.ClientConnection.PlayerSessionId = matchstatusResult.playerSessionId;
            }
            if (this.ClientConnection.MatchSuccess)
            {
                SetMainUI(UIType.PLAY);
                DisconnectToServer();
                SceneManager.LoadScene(this.ClientConnection.WorldId);
            }
            else
            {
                if (this.ClientConnection.PollingCount < 120)
                {
                    // Send requests about 2minutes
                    StartCoroutine(MatchStatusPolling());
                }
                else
                {
                    LogModule.WriteToLogFile("[ClientModule] Connection Error. Start later");
                    if (ConnectionStatus != null)
                    {
                        ConnectionStatus.text = "Connection Error";
                    }
                }
            }
        }
    }
示例#21
0
    public void SignInProcess(string inputName)
    {
        LogModule.WriteToLogFile("[ClientModule] Sign In Process");
        PlayerId = inputName;

#if UNITY_EDITOR
        if (LocalTest)
        {
            Debug.Log("Local Test Sign In");
            SetMainUI(UIType.PLAY);
            this.ClientConnection.Addess          = "127.0.0.1";
            this.ClientConnection.Port            = 7777;
            this.ClientConnection.PlayerSessionId = "Player!";
            DisconnectToServer();
            SceneManager.LoadScene(this.ClientConnection.WorldId);
        }
        else
        {
            MoveToWorld("Map001");
        }
#else
        MoveToWorld("Map001");
#endif
    }
示例#22
0
 private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
 {
     LogModule.WriteToLogFile("[ClientModule] On SceneLoad - " + scene.name);
     // If scene is about game, connect to game server
     ConnectToServer();
 }