1. 程式人生 > >坦克大戰 第六章 網路基礎 之客戶端:

坦克大戰 第六章 網路基礎 之客戶端:



using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using UnityEngine.UI; public class Walk : MonoBehaviour {    
//socket和緩衝區     Socket socket;     const int BUFFER_SIZE = 1024;     public byte [] readBuff = new byte [BUFFER_SIZE];     //玩家列表     Dictionary < string
, GameObject > players = new Dictionary < string , GameObject >();     //訊息列表     List < string > msgList = new List < string >();     //Player預設    
public GameObject prefab;     //自己的IP和埠     string id;     //新增玩家     void AddPlayer( string id, Vector3 pos)     {         GameObject player = ( GameObject )Instantiate(prefab, pos, Quaternion .identity);         TextMesh textMesh = player.GetComponentInChildren< TextMesh >();         textMesh.text = id;         players.Add(id, player);     }     //傳送位置協議     void SendPos()     {         GameObject player = players[id];         Vector3 pos = player.transform.position;         //組裝協議         string str = "POS " ;         str += id + " " ;         str += pos.x.ToString() + " " ;         str += pos.y.ToString() + " " ;         str += pos.z.ToString() + " " ;         byte [] bytes = System.Text. Encoding .Default.GetBytes(str);         socket.Send(bytes);         Debug .Log( "傳送 " + str);     }     //傳送離開協議     void SendLeave()     {         //組裝協議         string str = "LEAVE " ;         str += id + " " ;         byte [] bytes = System.Text. Encoding .Default.GetBytes(str);         socket.Send(bytes);         Debug .Log( "傳送 " + str);     }     //移動     void Move()     {         if (id == "" )             return ;         GameObject player = players[id];         //上         if ( Input .GetKey( KeyCode .UpArrow))         {             player.transform.position += new Vector3 (0, 0, 1);             SendPos();         }         //下         else if ( Input .GetKey( KeyCode .DownArrow))         {             player.transform.position += new Vector3 (0, 0, -1); ;             SendPos();         }         //左         else if ( Input .GetKey( KeyCode .LeftArrow))         {             player.transform.position += new Vector3 (-1, 0, 0);             SendPos();         }         //右         else if ( Input .GetKey( KeyCode .RightArrow))         {             player.transform.position += new Vector3 (1, 0, 0);             SendPos();         }     }     //離開     void OnDestory()     {         SendLeave();     }     //開始     void Start ()     {         Connect();         //請求其他玩家列表,略         //把自己放在一個隨機位置         UnityEngine. Random .seed = ( int ) DateTime .Now.Ticks;         float x = 100 + UnityEngine. Random .Range(-30, 30);         float y = 0;         float z = 100 + UnityEngine. Random .Range(-30, 30);         Vector3 pos = new Vector3 (x, y, z);         AddPlayer(id, pos);         //同步         SendPos();     }     //連結     void Connect()     {         //Socket         socket = new Socket ( AddressFamily .InterNetwork,                                  SocketType .Stream, ProtocolType .Tcp);         //Connect         socket.Connect( "127.0.0.1" , 1234);         id = socket.LocalEndPoint.ToString();         //Recv         socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags .None, ReceiveCb, null );     }     //接收回調     private void ReceiveCb( IAsyncResult ar)     {         try         {             int count = socket.EndReceive(ar);             //資料處理             string str = System.Text. Encoding .UTF8.GetString(readBuff, 0, count);             msgList.Add(str);             //繼續接收                   socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags .None, ReceiveCb, null );         }         catch ( Exception e)         {             socket.Close();         }     }     void Update ()     {         //處理訊息列表         for ( int i = 0; i < msgList.Count; i++)             HandleMsg();         //移動         Move();     }     //處理訊息列表     void HandleMsg()     {         //獲取一條訊息         if (msgList.Count <= 0)             return ;         string str = msgList[0];         msgList.RemoveAt(0);         //根據協議做不同的訊息處理         string [] args = str.Split( ' ' );         if (args[0] == "POS" )         {             OnRecvPos(args[1], args[2], args[3], args[4]);         }         else if (args[0] == "LEAVE" )         {             OnRecvLeave(args[1]);         }     }     //處理更新位置的協議     public void OnRecvPos( string id, string xStr, string yStr, string zStr)     {         //不更新自己的位置         if (id == this .id)             return ;         //解析協議         float x = float .Parse(xStr);         float y = float .Parse(yStr);         float z = float .Parse(zStr);         Vector3 pos = new Vector3 (x, y, z);         //已經初始化該玩家         if (players.ContainsKey(id))         {             players[id].transform.position = pos;         }         //尚未初始化該玩家         else         {             AddPlayer(id, pos);         }     }     //處理玩家離開的協議     public void OnRecvLeave( string id)     {         if (players.ContainsKey(id))         {             Destroy(players[id]);             players[id] = null ;         }     } }