示例#1
0
    //send find match msg to server
    public void FindRoom()
    {
        Debug.Log("FindRoom called");

        MultiGameState    = GameState.Game_Match;
        TheUserMatchState = UserMatchState.FindRoom;

        SprotoType.matchMsg.request req = new SprotoType.matchMsg.request();
        req.matchMsgType = (int)MatchMsgType.Match_FindRoom;
        //mChen
        //switch (GameManager.TheGameMode)
        //{
        //    case GameMode.MultiGame_1v1:
        //        req.matchInfo = ((int)MatchType.Normal_1v1).ToString();
        //        break;
        //    case GameMode.MultiGame_2v2:
        //        req.matchInfo = ((int)MatchType.Normal_2v2).ToString();
        //        break;
        //    case GameMode.MultiGame_3v3:
        //        req.matchInfo = ((int)MatchType.Normal_3v3).ToString();
        //        break;
        //}
        req.matchInfo = ((int)MatchType.Normal_1v1).ToString();

        NetSender.Send <Protocol.matchMsg>(req);
    }
示例#2
0
    public void TryToJoinMatch()
    {
        Debug.Log("TryToJoinMatch called");
        //TheUserMatchState = UserMatchState.JoinedRoom;

        SprotoType.matchMsg.request req = new SprotoType.matchMsg.request();
        req.matchMsgType = (int)MatchMsgType.Match_TryToJoinMatch;
        NetSender.Send <Protocol.matchMsg>(req);
    }
示例#3
0
    public void LeaveMatchToRoom()
    {
        Debug.Log("LeaveMatchToRoom called");

        if (TheUserMatchState == UserMatchState.PlayingMatch || TheUserMatchState == UserMatchState.WaitToJoinNextMatch)
        {
            MultiGameState    = GameState.Game_Match;
            TheUserMatchState = UserMatchState.JoinedRoom;

            SprotoType.matchMsg.request req = new SprotoType.matchMsg.request();
            req.matchMsgType = (int)MatchMsgType.Match_LeaveMatchToRoom;
            NetSender.Send <Protocol.matchMsg>(req);
        }
    }
示例#4
0
    private void SetupNetReceiverHandler()
    {
        NetReceiver.AddHandler <Protocol.handshake>((_) =>
        {
            Debug.Log("handshake");
            SprotoType.handshake.request req = _ as handshake.request;
            switch (TheUserLoginState)
            {
            case UserLoginState.LoginStart:
                {
                    //Debug.Log("challenge receive ");
                    _challengeStr = Convert.FromBase64String(req.msg);

                    DH64 dhforKey = new DH64();
                    dhforKey.KeyPair(out _privateKey, out _publicKey);
                    SprotoType.handshake.request clientkey = new handshake.request();

                    clientkey.msg = Convert.ToBase64String(BitConverter.GetBytes(_publicKey));

                    clientkey.socketfd = req.socketfd;
                    NetSender.Send <Protocol.handshake>(clientkey);

                    Debug.Log("challengeStr" + _challengeStr + " ori " + req.msg + " fd " + clientkey.socketfd);
                    TheUserLoginState = UserLoginState.LoginPublicServerKey;
                }
                break;

            case UserLoginState.LoginPublicServerKey:
                {
                    //string serverKey = System.Text.Encoding.Default.GetString(Convert.FromBase64String(req.msg));
                    byte[] ServerKey = Convert.FromBase64String(req.msg);

                    ulong serverKey = BitConverter.ToUInt64(ServerKey, 0);
                    _secretKey      = DH64.Secret(_privateKey, serverKey);
                    SprotoType.handshake.request challengeMsg = new handshake.request();

                    challengeMsg.msg =
                        Convert.ToBase64String(
                            BitConverter.GetBytes(
                                HMac64.hmac(
                                    BitConverter.ToUInt64(_challengeStr, 0),
                                    _secretKey)));

                    challengeMsg.socketfd = req.socketfd;
                    NetSender.Send <Protocol.handshake>(challengeMsg);
                    TheUserLoginState = UserLoginState.LoginCheckSecret;
                }
                break;

            case UserLoginState.LoginCheckSecret:
                {
                    if (Convert.ToBase64String(Encoding.UTF8.GetBytes(challengeSuccess)) == req.msg)
                    {
                        if (UserName != string.Empty)
                        {
                            Debug.Log("login " + UserName);
                            string token = string.Format("{0}:{1}",
                                                         Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName)),
                                                         Convert.ToBase64String(Encoding.UTF8.GetBytes(PassWord)));

                            SprotoType.handshake.request tokenMsg = new handshake.request
                            {
                                msg      = DesCrypt.desencode(_secretKey, token),
                                socketfd = req.socketfd
                            };

                            NetSender.Send <Protocol.handshake>(tokenMsg);

                            TheUserLoginState = UserLoginState.LoginCheckTokenResult;
                        }
                        else
                        {
                            Debug.Log("register");
                            DisplayName  = RandomName.GetRandomName();
                            string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(DisplayName));
                            SprotoType.handshake.request tokenMsg = new handshake.request
                            {
                                msg      = DesCrypt.desencode(_secretKey, token),
                                socketfd = req.socketfd
                            };

                            NetSender.Send <Protocol.handshake>(tokenMsg);
                            TheUserLoginState = UserLoginState.LoginRegistResult;
                        }
                    }
                    else if (Convert.ToBase64String(Encoding.UTF8.GetBytes(challengeFailed)) == req.msg)
                    {
                        Debug.Log("sercet incorrect!");
                        //error handle
                        TheUserLoginState = UserLoginState.LoginFailed;
                    }
                }
                break;

            case UserLoginState.LoginRegistResult:
                {
                    var msg      = Encoding.UTF8.GetString(Convert.FromBase64String(req.msg));
                    var msgArray = msg.Split(':');
                    UserName     = Encoding.UTF8.GetString(Convert.FromBase64String(msgArray[0]));
                    PassWord     = Encoding.UTF8.GetString(Convert.FromBase64String(msgArray[1]));

                    Loom.QueueOnMainThread(() =>
                    {
                        //save registed info
                        PlayerPrefs.SetString("username", UserName);
                        //GameManager.NetWorkClient.UserName = String.Empty;
                        PlayerPrefs.SetString("password", PassWord);
                        PlayerPrefs.SetString("displayname", DisplayName);
                        Debug.Log("saving name " + UserName + " : " + PassWord);
                        PlayerPrefs.Save();
                    });
                    Debug.Log("name " + UserName + " : " + PassWord);

                    //Thread.Sleep(5);
                    TheUserLoginState = UserLoginState.LoginSuccess;
                }
                break;

            case UserLoginState.LoginCheckTokenResult:
            case UserLoginState.LoginSuccess:
                {
                    if (Convert.ToBase64String(Encoding.UTF8.GetBytes(challengeSuccess)) == req.msg)
                    {
                        //Thread.Sleep(5);
                        Debug.Log("token right");

                        TheUserLoginState = UserLoginState.LoginSuccess;

                        // mChen
                        //if(MultiGameState == GameState.Game_NullState)
                        //{
                        //    FindMatch();
                        //}
                    }
                    else if (Convert.ToBase64String(Encoding.UTF8.GetBytes(challengeFailed)) == req.msg)
                    {
                        //error handle
                        TheUserLoginState = UserLoginState.LoginFailed;
                    }
                }
                break;
            }
            //NetSender.Send<Protocol.handshake>(req);
            //Debug.Log(TheUserLoginState.ToString());
            return(null);
        });

        NetReceiver.AddHandler <Protocol.matchMsg>((_) =>
        {
            SprotoType.matchMsg.request req = _ as matchMsg.request;

            switch (req.matchMsgType)
            {
            case (Int64)MatchMsgType.Match_PlayerJoinedRoom:
                int playerTeamType = Convert.ToInt32(req.matchInfo);
                TheUserMatchState  = UserMatchState.JoinedRoom;
                Debug.Log("NetReceiver: matchMsg: MatchMsgType.Match_PlayerJoinRoom: playerTeamType=" + playerTeamType);
                break;

            case (Int64)MatchMsgType.Match_CountDownTime:
                float countDowmTime = Convert.ToSingle(req.matchInfo) / 100;
                Debug.Log("NetReceiver: matchMsg: MatchMsgType.Match_CountDownTime =" + countDowmTime);
                // UI
                Loom.QueueOnMainThread(() =>
                {
                    UIManager.GetInstance().ShowMatchStartCountDown(countDowmTime);
                });
                break;

            case (Int64)MatchMsgType.Match_TryToJoinMatch:
                int result = Convert.ToInt32(req.matchInfo);
                Debug.Log("NetReceiver: matchMsg: MatchMsgType.Match_TryToJoinMatch: result=" + result);
                MultiGameState = GameState.Game_Match;
                if (result == 0)
                {
                    TheUserMatchState = UserMatchState.WaitToJoinNextMatch;
                    Loom.QueueOnMainThread(() =>
                    {
                        UIManager.GetInstance().ShowWaitToJoinNextMatchLabel();
                    });
                }
                else if (result == 1)
                {
                    TheUserMatchState = UserMatchState.PlayingMatch;
                    Loom.QueueOnMainThread(() =>
                    {
                        UIManager.GetInstance().HideWaitToJoinNextMatchLabel();
                    });
                }
                else
                {
                    Debug.Log("error TryToJoinMatch result from Server" + result);
                    throw new Exception("error TryToJoinMatch result from Server");
                }
                break;

            //case (Int64)MatchMsgType.Match_CancelMatching:
            //    if (QuitMatchingMsg != null)
            //    {
            //        QuitMatchingMsg(this, EventArgs.Empty);
            //    }
            //    break;

            default:
                Debug.Log("error match type" + req.matchMsgType);
                throw new Exception("error msg type");
            }
            return(null);
        });

        NetReceiver.AddHandler <Protocol.usersInfoMsg>((_) =>
        {
            if (MultiGameState == GameState.Game_NullState)
            {
                return(null);
            }
            Debug.Log("get usersInfoMsg");

            SprotoType.usersInfoMsg.request req           = _ as SprotoType.usersInfoMsg.request;
            GameObjectsManager.s_LocalPlayerIndexInGlobal = (int)req.curUserGlobalIndex;
            //Debug.Log("get player index in global: " + GameObjectsManager.s_LocalPlayerIndexInGlobal);

            //Create players
            Loom.QueueOnMainThread(() =>
            {
                AllPlayers.Clear();
                GameObjectsManager.GetInstance().ClearPlayers();

                Debug.Log("received usersInfoMsg:");
                foreach (SprotoType.UserInfo serverPlayerinfo in req.userArray)
                {
                    PlayerTeam.PlayerTeamType teamType = (PlayerTeam.PlayerTeamType)serverPlayerinfo.playerTeamType;
                    PlayerTeam team = GameObjectsManager.GetInstance().GetPlayerTeam(teamType);
                    int userState   = (int)serverPlayerinfo.userState;

                    Debug.Log("     UserIndexInGlobal=" + serverPlayerinfo.playerIndex + " UserName="******" userState=" + userState + " TeamType=" + teamType);

                    if (serverPlayerinfo.playerIndex == req.curUserGlobalIndex)
                    {
                        // is local player

                        if (userState == (int)UserMatchState.PlayingMatch)
                        {
                            GameObjectsManager.s_LocalHumanTeamType = teamType;
                        }
                    }

                    int playerIndexInTeam = -1;
                    if (userState == (int)UserMatchState.PlayingMatch)
                    {
                        // create a new player

                        playerIndexInTeam = team.AddAPlayer(false);
                    }

                    // set AllPlayers
                    AllPlayers.Add(new MultiPlayerInfo
                    {
                        PlayIndexInGlobal = serverPlayerinfo.playerIndex,
                        PlayerName        = serverPlayerinfo.username,
                        SkinId            = 0,
                        PlayerId          = 1,
                        ThePlayerTeamType = teamType,
                        PlayerIndexInTeam = playerIndexInTeam
                    });
                }
            });

            //TheUserMatchState = UserMatchState.AllPlayersJoinedRoom;
            return(null);
        });

        NetReceiver.AddHandler <Protocol.waitforstart>((_) =>
        {
            Debug.Log("Second half start!!");
            var res = _ as SprotoType.waitforstart.request;
            //mChen
            //switch (GameManager.GetInstance().TheGamePrePeriod)
            //{
            //    case GamePeriod.Opening:
            //        break;
            //    case GamePeriod.FirstHalf:
            //        break;
            //    case GamePeriod.Halftime:
            //        break;
            //    case GamePeriod.CutsceneAfterScoredOr24SecondsViolation:
            //        break;
            //    case GamePeriod.WairForGameToContinue:
            //        break;
            //    case GamePeriod.SecondHalf:
            //        GameManager.GetInstance().HalfTimeReadyFrame = res.readyFrame;
            //        break;
            //    case GamePeriod.Ending:
            //        break;
            //    default:
            //        throw new ArgumentOutOfRangeException();
            //}

            return(null);
        });

        NetReceiver.AddHandler <Protocol.gameTick>((_) =>
        {
            //Debug.Log("response called");
            if (false)//mChen if (GameManager.TheGameMode > GameMode.MultiGame_3v3)
            {
                //when single mode, do not handle this server tick
                return(null);
            }

            if (MultiGameState == GameState.Game_Match)
            {
                MultiGameState = GameState.Game_Running;

                Loom.QueueOnMainThread(() =>
                {
                    UIManager.GetInstance().HideMatchStartCountDown();
                });

                //mChen
                _sendHeartBeatThread = new Thread(SendHeartBeatMsg)
                {
                    IsBackground = true
                };
                //防止后台现成。相反需要后台线程就设为false
                _sendHeartBeatThread.Start();
                while (_sendHeartBeatThread.IsAlive == false)
                {
                }
            }

            SprotoType.gameTick.request res = _ as gameTick.request;
            {
                // bool bOnlyFrameInfo = true;

                if (res.HasButtonMsg)
                {
                    //mChen
                    //foreach (var btnMsg in res.buttonMsg)
                    //{
                    //    ButtonInfo msg = new ButtonInfo
                    //    {
                    //        TeamType =
                    //            (PlayerTeamType)((btnMsg.playerIndex) / GameManager.TeamPlayerNum),
                    //        PlayerIndexInTeam = (btnMsg.playerIndex) % GameManager.TeamPlayerNum,
                    //        FrameNum = res.frame,
                    //        Action = (ButtonAction)btnMsg.btnAction,
                    //        Type = (ButtonType)btnMsg.btnType
                    //    };

                    //    if (btnMsg.HasBtnValueX)
                    //    {
                    //        msg.Value.x = (float)BitConverter.ToDouble(BitConverter.GetBytes(btnMsg.btnValueX), 0);
                    //        msg.Value.y = (float)BitConverter.ToDouble(BitConverter.GetBytes(btnMsg.btnValueY), 0); ;
                    //    }
                    //    ControlManager.GetInstance().AddControlInfo(msg);
                    //    //Debug.Log("Button msg");
                    //}

                    // bOnlyFrameInfo = false;
                }

                //_controllerMsg.Clear();
                if (res.HasControlMsg)
                {
                    //Debug.Log("controller called");
                    //List < ControlMsg > tempList = new List<ControlMsg>();

                    foreach (var resControl in res.controlMsg)
                    {
                        //mChen
                        //DPadInfo msg = new DPadInfo
                        //{
                        //    FrameNum = res.frame,
                        //    TeamType = (PlayerTeamType)(resControl.playerIndex / GameManager.TeamPlayerNum),
                        //    PlayerIndexInTeam = resControl.playerIndex % GameManager.TeamPlayerNum,
                        //    //H = Convert.ToSingle(resControl.x),
                        //    //V = Convert.ToSingle(resControl.y)
                        //    H = (float)BitConverter.ToDouble(BitConverter.GetBytes(resControl.x), 0),
                        //    V = (float)BitConverter.ToDouble(BitConverter.GetBytes(resControl.y), 0)
                        //};

                        //ControlManager.GetInstance().AddControlInfo(msg);
#if false
                        if (ControlManager.GetInstance().GameFrameNum % 150 == 1)
                        {
                            GameManager.GetInstance().InfoStr += string.Format("\n dpad info {0} {1} at frame {2}",
                                                                               msg.H, msg.V, ControlManager.GetInstance().GameFrameNum);
                        }
#endif
                        // Debug.LogFormat("dpad msg frame {0} : h {1} v {2} ", res.frame, msg.H, msg.V);
                    }


                    // bOnlyFrameInfo = false;
                }

                if (res.HasPlayersGamePlayMsg)
                {
                    Loom.QueueOnMainThread(() =>
                    {
                        foreach (var playerGamePlayMsg in res.playersGamePlayMsg)
                        {
                            int playerIndex = (int)playerGamePlayMsg.playerIndex;
                            float posX      = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.posX), 0);
                            float posY      = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.posY), 0);
                            float posZ      = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.posZ), 0);
                            float angleX    = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.angleX), 0);
                            float angleY    = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.angleY), 0);
                            float angleZ    = (float)BitConverter.ToDouble(BitConverter.GetBytes(playerGamePlayMsg.angleZ), 0);
                            //Debug.Log("playerInfoMsg:" + playerGamePlayMsg.playerIndex + " pos:" + posX + posY + posZ);

                            if (playerIndex == GameObjectsManager.s_LocalPlayerIndexInGlobal)
                            {
                            }
                            else
                            {
                                PlayerTeam.PlayerTeamType teamType = AllPlayers[playerIndex].ThePlayerTeamType;
                                int playerIndexInTeam = AllPlayers[playerIndex].PlayerIndexInTeam;
                                PlayerBase player     = GameObjectsManager.GetInstance().GetPlayer(teamType, playerIndexInTeam);
                                if (player != null)
                                {
                                    player.transform.position    = new Vector3(posX, posY, posZ);
                                    player.transform.eulerAngles = new Vector3(angleX, angleY, angleZ);
                                }
                            }
                        }
                    });
                }

                //添加一般帧信息
                //if (bOnlyFrameInfo)
                {
                    //mChen ControlManager.GetInstance().AddControlInfo(res.frame);
                }
            }
            return(null);
        });

        NetReceiver.AddHandler <Protocol.restoreStates>((_) =>
        {
            var req           = _ as SprotoType.restoreStates.request;
            TheUserMatchState = (UserMatchState)req.serverState;
            Debug.Log("resotre user state now " + TheUserMatchState.ToString());
            var infoArray = req.stateInfo.Split(':');

            switch (req.serverState)
            {
            case (int)UserMatchState.FindRoom:
                ParseFindMatchMsg(infoArray);
                TheUserMatchState = UserMatchState.FindRoom;
                //mChen Loom.QueueOnMainThread(GameUIManager.GetInstance().UIChangeToMatching);
                //GameUIManager.GetInstance().UIChangeToMatching();//go to matching ui
                break;
            }
            return(null);
        });
    }