Guest User

Untitled

a guest
Jun 17th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.13 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.SceneManagement;
  4. using UnityEngine.Networking;
  5. using UnityEngine.Networking.Types;
  6. using UnityEngine.Networking.Match;
  7. using System.Collections;
  8. using WebSocketSharp;
  9. using Newtonsoft.Json;
  10. using System.Collections.Generic;
  11. using System;
  12. using System.Diagnostics;
  13.  
  14. namespace Prototype.NetworkLobby
  15. {
  16.     public class LobbyManager : NetworkLobbyManager
  17.     {
  18.         static short MsgKicked = MsgType.Highest + 1;
  19.  
  20.         static public LobbyManager s_Singleton;
  21.  
  22.         static public WebSocket ws;
  23.  
  24.  
  25.         [Header("Unity UI Lobby")]
  26.         [Tooltip("Time in second between all players ready & match start")]
  27.         public float prematchCountdown = 5.0f;
  28.  
  29.         [Space]
  30.         [Header("UI Reference")]
  31.         public LobbyTopPanel topPanel;
  32.  
  33.         public RectTransform mainMenuPanel;
  34.         public RectTransform lobbyPanel;
  35.  
  36.         public LobbyInfoPanel infoPanel;
  37.         public LobbyCountdownPanel countdownPanel;
  38.         public GameObject addPlayerButton;
  39.  
  40.         protected RectTransform currentPanel;
  41.  
  42.         public Button backButton;
  43.  
  44.         public Text statusInfo;
  45.         public Text hostInfo;
  46.  
  47.         //Client numPlayers from NetworkManager is always 0, so we count (throught connect/destroy in LobbyPlayer) the number
  48.         //of players, so that even client know how many player there is.
  49.         [HideInInspector]
  50.         public int _playerNumber = 0;
  51.  
  52.         //used to disconnect a client properly when exiting the matchmaker
  53.         [HideInInspector]
  54.         public bool _isMatchmaking = false;
  55.  
  56.         protected bool _disconnectServer = false;
  57.  
  58.         protected ulong _currentMatchID;
  59.  
  60.         protected LobbyHook _lobbyHooks;
  61.  
  62.         private bool addNewPlayer = false;
  63.         private Payload tempPayload;
  64.  
  65.         private bool refreshPlayer = false;
  66.         private Payload refreshPayload;
  67.  
  68.         public static Dictionary<string, RectTransform> screens;
  69.         public static Dictionary<string, Action<Payload>> serverCommands;
  70.         public static Dictionary<string, Action<Payload>> playerCommands;
  71.         public static Dictionary<string, Action<Payload>> adminCommands;
  72.         public static Dictionary<string, Dictionary<string, Action<Payload>>> commandsSet;
  73.  
  74.         public float t;
  75.         public float gg = 0;
  76.         public bool speedTest;
  77.         public float deltaSpeed;
  78.  
  79.         void Update()
  80.         {
  81.             if (addNewPlayer)
  82.             {
  83.                 adminCommands["addPlayer"](tempPayload);
  84.                 addNewPlayer = false;
  85.             }
  86.  
  87.             if (refreshPlayer)
  88.             {
  89.                 playerCommands["refresh"](refreshPayload);
  90.                 refreshPlayer = false;
  91.             }
  92.  
  93.             t += Time.deltaTime;
  94.  
  95.             if (speedTest && gg <= 6)
  96.             {
  97.                 UnityEngine.Debug.Log("speed test");
  98.                 StartCoroutine(SpeedTestt());
  99.             }
  100.  
  101.             if (gg >= 6)
  102.             {
  103.                
  104.                 User user = new User();
  105.                 user.userName = "1";
  106.                 user.userType = "Admin";
  107.  
  108.                 Payload newPayload = new Payload();
  109.                 newPayload.user = user;
  110.                 newPayload.speedTest = deltaSpeed;
  111.  
  112.                 UnityEngine.Debug.Log("deltaSpeed in payload");
  113.                 UnityEngine.Debug.Log(newPayload.speedTest);
  114.  
  115.                 serverCommands["broadCastSpeedTest"](newPayload);
  116.  
  117.                 deltaSpeed = 0;
  118.                 speedTest = false;
  119.                 gg = 0;
  120.             }
  121.         }
  122.  
  123.         public void StartSpeedTest()
  124.         {
  125.             speedTest = true;
  126.         }
  127.  
  128.         void Start()
  129.         {
  130.             s_Singleton = this;
  131.             _lobbyHooks = GetComponent<Prototype.NetworkLobby.LobbyHook>();
  132.             currentPanel = mainMenuPanel;
  133.  
  134.             adminCommands = new Dictionary<string, Action<Payload>> {
  135.                 { "addPlayer", (payload) => {
  136.                         LobbyPlayerList._instance.AddPlayer(GetPlayer(payload));
  137.                     }
  138.                 },
  139.                 { "playerConnected", (payload) => {
  140.                         tempPayload = payload;
  141.                         addNewPlayer = true;
  142.                     }
  143.                 },
  144.                 { "startDemo", (payload) => {
  145.                         User newAdmin = new User();
  146.                         newAdmin.userName = "1";
  147.                         newAdmin.userType = "Admin";
  148.  
  149.                         payload.user = newAdmin;
  150.  
  151.                         Command command = new Command();
  152.                         command.command = "startDemo";
  153.                         command.setType = "playerCommands";
  154.  
  155.                         Message message = new Message();
  156.                         message.payload = payload;
  157.                         message.command = command;
  158.                         message.target = payload.target;
  159.  
  160.                         string json = JsonConvert.SerializeObject(message);
  161.                         ws.Send(json);
  162.                     }
  163.                 }
  164.             };
  165.  
  166.             playerCommands = new Dictionary<string, Action<Payload>> {
  167.                 { "refresh", (payload) => {
  168.                         LobbyPlayerList._instance.UpdatePlayer(payload.user, payload.stateData);
  169.                     }
  170.                 },
  171.                 { "refreshData", (payload) => {
  172.                         refreshPayload = payload;
  173.                         refreshPlayer = true;
  174.                     }
  175.                 }
  176.             };
  177.  
  178.             serverCommands = new Dictionary<string, Action<Payload>> {
  179.                 { "createLobby", (payload) => {
  180.                         User user = new User();
  181.                         user.userName = "1";
  182.                         user.userType = "Admin";
  183.  
  184.                         Payload newPayload = new Payload();
  185.                         newPayload.user = user;
  186.  
  187.                         Command command = new Command();
  188.                         command.setType = "serverCommands";
  189.                         command.command = "createLobby";
  190.  
  191.                         Message message = new Message();
  192.                         message.payload = payload;
  193.                         message.command = command;
  194.  
  195.                         string json = JsonConvert.SerializeObject(message);
  196.                         ws.Send(json);
  197.                     }
  198.                 },
  199.                 { "broadCastSpeedTest", (payload) => {
  200.                         Command command = new Command();
  201.                         command.setType = "serverCommands";
  202.                         command.command = "broadCastSpeedTest";
  203.  
  204.                         Message message = new Message();
  205.                         message.payload = payload;
  206.                         message.command = command;
  207.  
  208.                         string json = JsonConvert.SerializeObject(message);
  209.                         ws.Send(json);
  210.                     }
  211.                 }
  212.             };
  213.  
  214.             screens = new Dictionary<string, RectTransform> {
  215.                 { "mainMenu", s_Singleton.mainMenuPanel},
  216.                 { "lobby", s_Singleton.lobbyPanel }
  217.             };
  218.  
  219.             commandsSet = new Dictionary<string, Dictionary<string, Action<Payload>>> {
  220.                 { "playerCommands", playerCommands },
  221.                 { "adminCommands", adminCommands },
  222.                 { "serverCommands", serverCommands }
  223.             };
  224.  
  225.             backButton.gameObject.SetActive(false);
  226.             GetComponent<Canvas>().enabled = true;
  227.                
  228.             ws = new WebSocket("ws://localhost:8999");
  229.  
  230.  
  231.             User admin = new User();
  232.             admin.userType = "Admin";
  233.             admin.userName = "1";
  234.                
  235.             Payload initPayload = new Payload();
  236.             initPayload.user = admin;
  237.  
  238.             Command newCommand = new Command();
  239.             newCommand.setType = "serverCommands";
  240.             newCommand.command = "reg";
  241.  
  242.             Message newMessage = new Message();
  243.             newMessage.command = newCommand;
  244.             newMessage.payload = initPayload;
  245.  
  246.             string jsonAdmin = JsonConvert.SerializeObject(newMessage);
  247.             ws.OnMessage += (sender, e) => {
  248.                 Message message = JsonConvert.DeserializeObject<Message>(e.Data);
  249.                 Command command = message.command;
  250.                
  251.                 Dictionary<string, Action<Payload>> currentCommandSet = commandsSet[command.setType];
  252.  
  253.                 currentCommandSet[command.command](message.payload);
  254.             };
  255.  
  256.             ws.Connect();
  257.             ws.Send(jsonAdmin);
  258.  
  259.             DontDestroyOnLoad(gameObject);
  260.  
  261.             SetServerInfo("Offline", "None");
  262.         }
  263.  
  264.         public LobbyPlayer GetPlayer(Payload payload)
  265.         {
  266.             User user = payload.user;
  267.             GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject;
  268.  
  269.             LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>();
  270.  
  271.             newPlayer.playerName = user.userName;
  272.             newPlayer.nameInput.text = user.userName;
  273.  
  274.             return newPlayer;
  275.         }
  276.  
  277.         public IEnumerator SpeedTestt()
  278.         {
  279.             yield return new WaitForSeconds(1f);
  280.             UnityEngine.Debug.Log("started");
  281.  
  282.             Console.WriteLine("Downloading file....");
  283.  
  284.             var watch = new Stopwatch();
  285.  
  286.             byte[] data;
  287.             using (var client = new System.Net.WebClient())
  288.             {
  289.                 watch.Start();
  290.                 data = client.DownloadData("http://dl.google.com/googletalk/googletalk-setup.exe?t=" + DateTime.Now.Ticks);
  291.                 watch.Stop();
  292.             }
  293.  
  294.             deltaSpeed = (float)(data.LongLength / watch.Elapsed.TotalSeconds / 100000f / 10f); // instead of [Seconds] property
  295.             UnityEngine.Debug.Log("deltaSpeed in speedtest");
  296.             UnityEngine.Debug.Log(deltaSpeed);
  297.  
  298.             gg++;
  299.         }
  300.  
  301.         public override void OnLobbyClientSceneChanged(NetworkConnection conn)
  302.         {
  303.             if (SceneManager.GetSceneAt(0).name == lobbyScene)
  304.             {
  305.                 if (topPanel.isInGame)
  306.                 {
  307.                     ChangeTo(lobbyPanel);
  308.                     if (_isMatchmaking)
  309.                     {
  310.                         if (conn.playerControllers[0].unetView.isServer)
  311.                         {
  312.                             backDelegate = StopHostClbk;
  313.                         }
  314.                         else
  315.                         {
  316.                             backDelegate = StopClientClbk;
  317.                         }
  318.                     }
  319.                     else
  320.                     {
  321.                         if (conn.playerControllers[0].unetView.isClient)
  322.                         {
  323.                             backDelegate = StopHostClbk;
  324.                         }
  325.                         else
  326.                         {
  327.                             backDelegate = StopClientClbk;
  328.                         }
  329.                     }
  330.                 }
  331.                 else
  332.                 {
  333.                     ChangeTo(mainMenuPanel);
  334.                 }
  335.  
  336.                 topPanel.ToggleVisibility(true);
  337.                 topPanel.isInGame = false;
  338.             }
  339.             else
  340.             {
  341.                 ChangeTo(null);
  342.  
  343.                 Destroy(GameObject.Find("MainMenuUI(Clone)"));
  344.  
  345.                 //backDelegate = StopGameClbk;
  346.                 topPanel.isInGame = true;
  347.                 topPanel.ToggleVisibility(false);
  348.             }
  349.         }
  350.  
  351.         public void HostStart()
  352.         {
  353.             ChangeTo(lobbyPanel);
  354.             backDelegate = StopHostClbk;
  355.             SetServerInfo("Hosting", networkAddress);
  356.  
  357.             User user = new User();
  358.             user.userName = "1";
  359.             user.userType = "Admin";
  360.  
  361.             Payload payload = new Payload();
  362.             payload.user = user;
  363.  
  364.             serverCommands["createLobby"](payload);
  365.         }
  366.  
  367.         public void ChangeTo(RectTransform newPanel)
  368.         {
  369.             if (currentPanel != null)
  370.             {
  371.                 currentPanel.gameObject.SetActive(false);
  372.             }
  373.  
  374.             if (newPanel != null)
  375.             {
  376.                 newPanel.gameObject.SetActive(true);
  377.             }
  378.  
  379.             currentPanel = newPanel;
  380.  
  381.             if (currentPanel != mainMenuPanel)
  382.             {
  383.                 backButton.gameObject.SetActive(true);
  384.             }
  385.             else
  386.             {
  387.                 backButton.gameObject.SetActive(false);
  388.                 SetServerInfo("Offline", "None");
  389.                 _isMatchmaking = false;
  390.             }
  391.         }
  392.  
  393.         public void DisplayIsConnecting()
  394.         {
  395.             var _this = this;
  396.             infoPanel.Display("Connecting...", "Cancel", () => { _this.backDelegate(); });
  397.         }
  398.  
  399.         public void SetServerInfo(string status, string host)
  400.         {
  401.             statusInfo.text = status;
  402.             hostInfo.text = host;
  403.         }
  404.  
  405.  
  406.         public delegate void BackButtonDelegate();
  407.         public BackButtonDelegate backDelegate;
  408.         public void GoBackButton()
  409.         {
  410.             backDelegate();
  411.             topPanel.isInGame = false;
  412.         }
  413.  
  414.         // ----------------- Server management
  415.  
  416.         public void AddLocalPlayer()
  417.         {
  418.             User user = new User();
  419.             user.userName = "1";
  420.             user.userType = "player";
  421.  
  422.             Payload payload = new Payload();
  423.             payload.user = user;
  424.             adminCommands["playerConnected"](payload);
  425.             //TryToAddPlayer();
  426.         }
  427.  
  428.         public void RemovePlayer(LobbyPlayer player)
  429.         {
  430.             player.RemovePlayer();
  431.         }
  432.  
  433.         public void SimpleBackClbk()
  434.         {
  435.             ChangeTo(mainMenuPanel);
  436.         }
  437.                  
  438.         public void StopHostClbk()
  439.         {
  440.             if (_isMatchmaking)
  441.             {
  442.                 matchMaker.DestroyMatch((NetworkID)_currentMatchID, 0, OnDestroyMatch);
  443.                 _disconnectServer = true;
  444.             }
  445.             else
  446.             {
  447.                 StopHost();
  448.             }
  449.  
  450.            
  451.             ChangeTo(mainMenuPanel);
  452.         }
  453.  
  454.         public void StopClientClbk()
  455.         {
  456.             StopClient();
  457.  
  458.             if (_isMatchmaking)
  459.             {
  460.                 StopMatchMaker();
  461.             }
  462.  
  463.             ChangeTo(mainMenuPanel);
  464.         }
  465.  
  466.         public void StopServerClbk()
  467.         {
  468.             StopServer();
  469.             ChangeTo(mainMenuPanel);
  470.         }
  471.  
  472.         class KickMsg : MessageBase { }
  473.         public void KickPlayer(NetworkConnection conn)
  474.         {
  475.             conn.Send(MsgKicked, new KickMsg());
  476.         }
  477.  
  478.  
  479.         public void KickedMessageHandler(NetworkMessage netMsg)
  480.         {
  481.             infoPanel.Display("Kicked by Server", "Close", null);
  482.             netMsg.conn.Disconnect();
  483.         }
  484.  
  485.         //===================
  486.  
  487.         public override void OnStartHost()
  488.         {
  489.             base.OnStartHost();
  490.  
  491.             ChangeTo(lobbyPanel);
  492.             backDelegate = StopHostClbk;
  493.             SetServerInfo("Hosting", networkAddress);
  494.         }
  495.  
  496.         public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
  497.         {
  498.             base.OnMatchCreate(success, extendedInfo, matchInfo);
  499.             _currentMatchID = (System.UInt64)matchInfo.networkId;
  500.         }
  501.  
  502.         public override void OnDestroyMatch(bool success, string extendedInfo)
  503.         {
  504.             base.OnDestroyMatch(success, extendedInfo);
  505.             if (_disconnectServer)
  506.             {
  507.                 StopMatchMaker();
  508.                 StopHost();
  509.             }
  510.         }
  511.  
  512.         //allow to handle the (+) button to add/remove player
  513.         public void OnPlayersNumberModified(int count)
  514.         {
  515.             _playerNumber += count;
  516.  
  517.             int localPlayerCount = 0;
  518.             foreach (PlayerController p in ClientScene.localPlayers)
  519.                 localPlayerCount += (p == null || p.playerControllerId == -1) ? 0 : 1;
  520.  
  521.             addPlayerButton.SetActive(localPlayerCount < maxPlayersPerConnection && _playerNumber < maxPlayers);
  522.         }
  523.  
  524.         // ----------------- Server callbacks ------------------
  525.  
  526.         //we want to disable the button JOIN if we don't have enough player
  527.         //But OnLobbyClientConnect isn't called on hosting player. So we override the lobbyPlayer creation
  528.         public override GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn, short playerControllerId)
  529.         {
  530.             GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject;
  531.  
  532.             LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>();
  533.             newPlayer.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  534.  
  535.  
  536.             for (int i = 0; i < lobbySlots.Length; ++i)
  537.             {
  538.                 LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  539.  
  540.                 if (p != null)
  541.                 {
  542.                     p.RpcUpdateRemoveButton();
  543.                     p.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  544.                 }
  545.             }
  546.  
  547.             return obj;
  548.         }
  549.  
  550.         public override void OnLobbyServerPlayerRemoved(NetworkConnection conn, short playerControllerId)
  551.         {
  552.             for (int i = 0; i < lobbySlots.Length; ++i)
  553.             {
  554.                 LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  555.  
  556.                 if (p != null)
  557.                 {
  558.                     p.RpcUpdateRemoveButton();
  559.                     p.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  560.                 }
  561.             }
  562.         }
  563.  
  564.         public override void OnLobbyServerDisconnect(NetworkConnection conn)
  565.         {
  566.             for (int i = 0; i < lobbySlots.Length; ++i)
  567.             {
  568.                 LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  569.  
  570.                 if (p != null)
  571.                 {
  572.                     p.RpcUpdateRemoveButton();
  573.                     p.ToggleJoinButton(numPlayers >= minPlayers);
  574.                 }
  575.             }
  576.  
  577.         }
  578.  
  579.         public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer)
  580.         {
  581.             //This hook allows you to apply state data from the lobby-player to the game-player
  582.             //just subclass "LobbyHook" and add it to the lobby object.
  583.  
  584.             if (_lobbyHooks)
  585.                 _lobbyHooks.OnLobbyServerSceneLoadedForPlayer(this, lobbyPlayer, gamePlayer);
  586.  
  587.             return true;
  588.         }
  589.  
  590.         // --- Countdown management
  591.  
  592.         public override void OnLobbyServerPlayersReady()
  593.         {
  594.             bool allready = true;
  595.             for(int i = 0; i < lobbySlots.Length; ++i)
  596.             {
  597.                 if(lobbySlots[i] != null)
  598.                     allready &= lobbySlots[i].readyToBegin;
  599.             }
  600.  
  601.             if(allready)
  602.                 StartCoroutine(ServerCountdownCoroutine());
  603.         }
  604.  
  605.         public IEnumerator ServerCountdownCoroutine()
  606.         {
  607.             float remainingTime = prematchCountdown;
  608.             int floorTime = Mathf.FloorToInt(remainingTime);
  609.  
  610.             while (remainingTime > 0)
  611.             {
  612.                 yield return null;
  613.  
  614.                 remainingTime -= Time.deltaTime;
  615.                 int newFloorTime = Mathf.FloorToInt(remainingTime);
  616.  
  617.                 if (newFloorTime != floorTime)
  618.                 {//to avoid flooding the network of message, we only send a notice to client when the number of plain seconds change.
  619.                     floorTime = newFloorTime;
  620.  
  621.                     for (int i = 0; i < lobbySlots.Length; ++i)
  622.                     {
  623.                         if (lobbySlots[i] != null)
  624.                         {//there is maxPlayer slots, so some could be == null, need to test it before accessing!
  625.                             (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(floorTime);
  626.                         }
  627.                     }
  628.                 }
  629.             }
  630.  
  631.             for (int i = 0; i < lobbySlots.Length; ++i)
  632.             {
  633.                 if (lobbySlots[i] != null)
  634.                 {
  635.                     (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(0);
  636.                 }
  637.             }
  638.  
  639.             ServerChangeScene(playScene);
  640.         }
  641.  
  642.         // ----------------- Client callbacks ------------------
  643.  
  644.         public override void OnClientConnect(NetworkConnection conn)
  645.         {
  646.             base.OnClientConnect(conn);
  647.  
  648.             infoPanel.gameObject.SetActive(false);
  649.  
  650.             conn.RegisterHandler(MsgKicked, KickedMessageHandler);
  651.  
  652.             if (!NetworkServer.active)
  653.             {//only to do on pure client (not self hosting client)
  654.                 ChangeTo(lobbyPanel);
  655.                 backDelegate = StopClientClbk;
  656.                 SetServerInfo("Client", networkAddress);
  657.             }
  658.         }
  659.  
  660.  
  661.         public override void OnClientDisconnect(NetworkConnection conn)
  662.         {
  663.             base.OnClientDisconnect(conn);
  664.             ChangeTo(mainMenuPanel);
  665.         }
  666.  
  667.         public override void OnClientError(NetworkConnection conn, int errorCode)
  668.         {
  669.             ChangeTo(mainMenuPanel);
  670.             infoPanel.Display("Cient error : " + (errorCode == 6 ? "timeout" : errorCode.ToString()), "Close", null);
  671.         }
  672.     }
  673. }
Add Comment
Please, Sign In to add comment