1. 程式人生 > >Unity 網路通訊(一)Unity Network 初步

Unity 網路通訊(一)Unity Network 初步

  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class server : MonoBehaviour {  
  4.     int Port = 10000;  
  5.     //OnGUI方法,所有GUI的繪製都需要在這個方法中實現   
  6.     void OnGUI(){  
  7.         //Network.peerType是端型別的狀態:   
  8.         //即disconnected, connecting, server 或 client四種   
  9.         switch(Network.peerType){  
  10.             //禁止客戶端連線執行, 伺服器未初始化   
  11.             case NetworkPeerType.Disconnected:  
  12.                 StartServer();  
  13.                 break;  
  14.             //運行於伺服器端   
  15.             case NetworkPeerType.Server:  
  16.                 OnServer();  
  17.                 break;  
  18.             //運行於客戶端   
  19.             case NetworkPeerType.Client:  
  20.                 break;  
  21.             //正在嘗試連線到伺服器   
  22.             case NetworkPeerType.Connecting:  
  23.                 break;  
  24.         }  
  25.     }  
  26.     void StartServer(){  
  27.         //當用戶點選按鈕的時候為true   
  28.         if (GUILayout.Button("建立伺服器")) {  
  29.             //初始化本機伺服器埠,第一個引數就是本機接收多少連線   
  30.             NetworkConnectionError error = Network.InitializeServer(12,Port,false);  
  31.             Debug.Log("錯誤日誌"+error);  
  32.         }  
  33.     }  
  34.     void OnServer(){  
  35.         GUILayout.Label("服務端已經執行,等待客戶端連線");  
  36.         //Network.connections是所有連線的玩家, 陣列[]   
  37.         //取客戶端連線數.    
  38.         int length = Network.connections.Length;  
  39.         //按陣列下標輸出每個客戶端的IP,Port   
  40.         for (int i=0; i<length; i++)  
  41.         {  
  42.             GUILayout.Label("客戶端"+i);  
  43.             GUILayout.Label("客戶端ip"+Network.connections[i].ipAddress);  
  44.             GUILayout.Label("客戶端埠"+Network.connections[i].port);  
  45.         }  
  46.         //當用戶點選按鈕的時候為true   
  47.         if (GUILayout.Button("斷開伺服器")){  
  48.             Network.Disconnect();  
  49.         }  
  50.     }  
  51.     /* 系統提供的方法,該方法只執行一次 */  
  52.     // Use this for initialization   
  53.     void Start () {  
  54.     }  
  55.     // Update is called once per frame   
  56.     void Update () {  
  57.     }  
  58. }