Unity3D 遊戲引擎之C#使用Socket與HTTP鏈接server數據傳輸包

近期比較忙。有段時間沒寫博客拉。近期項目中需要使用HTTP與Socket。雨鬆MOMO把本身這段時間學習的資料整理一下。php

有關Socket與HTTP的基礎知識MOMO就不贅述拉,不懂得朋友本身谷歌吧。咱們項目的需求是在登陸的時候使用HTTP請求。遊戲中其餘的請求都用Socket請求。比方人物移動同步座標。同步關卡等等。android

1.Socket算法

        Socket不要寫在腳本上。假設寫在腳本上游戲場景一旦切換,那麼這條腳本會被釋放掉。Socket會斷開鏈接。c#

場景切換完成後需要又一次在與server創建Socket鏈接,這樣會很是麻煩。因此咱們需要把Socket寫在一個單例的類中,不用繼承MonoBehaviour。這個樣例我模擬一下。主角在遊戲中移動,時時向服務端發送當前座標,當server返回同步座標時角色開始同步服務端新角色座標。數組

Socket在發送消息的時候採用的是字節數組,也就是說無論你的數據是 int float short object 都會將這些數據類型先轉換成byte[] 。 眼下在處理髮送的地方我使用的是數據包。也就是把(角色座標)結構體object轉換成byte[]發送, 這就牽扯一個問題, 怎樣把結構體轉成字節數組, 怎樣把字節數組迴轉成結構體。請你們接續閱讀。答案就在後面,哇咔咔。多線程

直接上代碼iphone

JFSocket.cs 該單例類不要綁定在不論什麼對象上異步

  1. using UnityEngine;     
  2. using System.Collections;     
  3. using System;     
  4. using System.Threading;     
  5. using System.Text;     
  6. using System.Net;     
  7. using System.Net.Sockets;     
  8. using System.Collections.Generic;     
  9. using System.IO;     
  10. using System.Runtime.InteropServices;     
  11. using System.Runtime.Serialization;     
  12. using System.Runtime.Serialization.Formatters.Binary;     
  13.          
  14. public class JFSocket     
  15. {     
  16.          
  17.     //Socket客戶端對象     
  18.     private Socket clientSocket;     
  19.     //JFPackage.WorldPackage是我封裝的結構體。     
  20.     //在與server交互的時候會傳遞這個結構體     
  21.     //當客戶端接到到server返回的數據包時。我把結構體add存在鏈表中。     
  22.     public List<JFPackage.WorldPackage> worldpackage;     
  23.     //單例模式     
  24.     private static JFSocket instance;     
  25.     public static JFSocket GetInstance()     
  26.     {     
  27.         if (instance == null)     
  28.         {     
  29.             instance = new JFSocket();     
  30.         }     
  31.         return instance;     
  32.      }           
  33.          
  34.     //單例的構造函數     
  35.     JFSocket()     
  36.     {     
  37.         //建立Socket對象, 這裏個人鏈接類型是TCP     
  38.         clientSocket = new Socket (AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);     
  39.         //serverIP地址     
  40.         IPAddress ipAddress = IPAddress.Parse ("192.168.1.100");     
  41.         //serverport     
  42.         IPEndPoint ipEndpoint = new IPEndPoint (ipAddress, 10060);     
  43.         //這是一個異步的創建鏈接,當鏈接創建成功時調用connectCallback方法     
  44.         IAsyncResult result = clientSocket.BeginConnect (ipEndpoint,new AsyncCallback (connectCallback),clientSocket);     
  45.         //這裏作一個超時的監測,當鏈接超過5秒還沒成功表示超時     
  46.         bool success = result.AsyncWaitHandle.WaitOne( 5000, true );     
  47.         if ( !success )     
  48.         {     
  49.             //超時     
  50.             Closed();     
  51.             Debug.Log("connect Time Out");     
  52.         }else  
  53.         {     
  54.             //與socket創建鏈接成功,開啓線程接受服務端數據。     
  55.             worldpackage = new List<JFPackage.WorldPackage>();     
  56.             Thread thread = new Thread(new ThreadStart(ReceiveSorket));     
  57.             thread.IsBackground = true;     
  58.             thread.Start();     
  59.         }     
  60.     }     
  61.          
  62.     private void connectCallback(IAsyncResult asyncConnect)     
  63.     {     
  64.         Debug.Log("connectSuccess");     
  65.     }     
  66.          
  67.     private void ReceiveSorket()     
  68.     {     
  69.         //在這個線程中接受server返回的數據     
  70.         while (true)     
  71.         {      
  72.          
  73.             if(!clientSocket.Connected)     
  74.             {     
  75.                 //與server斷開鏈接跳出循環     
  76.                 Debug.Log("Failed to clientSocket server.");     
  77.                 clientSocket.Close();     
  78.                 break;     
  79.             }     
  80.             try  
  81.             {     
  82.                 //接受數據保存至bytes其中     
  83.                 byte[] bytes = new byte[4096];     
  84.                 //Receive方法中會一直等待服務端回發消息     
  85.                 //假設沒有回發會一直在這裏等着。     
  86.                 int i = clientSocket.Receive(bytes);     
  87.                 if(i <= 0)     
  88.                 {     
  89.                     clientSocket.Close();     
  90.                     break;     
  91.                 }        
  92.          
  93.                 //這裏條件可依據你的狀況來推斷。

         

  94.                 //因爲我眼下的項目先要監測包頭長度,     
  95.                 //個人包頭長度是2,因此我這裏有一個推斷     
  96.                 if(bytes.Length > 2)     
  97.                 {     
  98.                     SplitPackage(bytes,0);     
  99.                 }else  
  100.                 {     
  101.                     Debug.Log("length is not  >  2");     
  102.                 }     
  103.          
  104.              }     
  105.              catch (Exception e)     
  106.              {     
  107.                 Debug.Log("Failed to clientSocket error." + e);     
  108.                 clientSocket.Close();     
  109.                 break;     
  110.              }     
  111.         }     
  112.     }        
  113.          
  114.     private void SplitPackage(byte[] bytes , int index)     
  115.     {     
  116.         //在這裏進行拆包。因爲一次返回的數據包的數量是不定的     
  117.         //因此需要給數據包進行查分。     
  118.         while(true)     
  119.         {     
  120.             //包頭是2個字節     
  121.             byte[] head = new byte[2];     
  122.             int headLengthIndex = index + 2;     
  123.             //把數據包的前兩個字節拷貝出來     
  124.             Array.Copy(bytes,index,head,0,2);     
  125.             //計算包頭的長度     
  126.             short length = BitConverter.ToInt16(head,0);     
  127.             //當包頭的長度大於0 那麼需要依次把一樣長度的byte數組拷貝出來     
  128.             if(length > 0)     
  129.             {     
  130.                 byte[] data = new byte[length];     
  131.                 //拷貝出這個包的全部字節數     
  132.                 Array.Copy(bytes,headLengthIndex,data,0,length);     
  133.                 //把數據包中的字節數組強制轉換成數據包的結構體     
  134.                 //BytesToStruct()方法就是用來轉換的     
  135.                 //這裏需要和大家的服務端程序商議。     
  136.                 JFPackage.WorldPackage wp = new JFPackage.WorldPackage();     
  137.                 wp = (JFPackage.WorldPackage)BytesToStruct(data,wp.GetType());     
  138.                 //把每個包的結構體對象加入至鏈表中。     
  139.                 worldpackage.Add(wp);     
  140.                 //將索引指向下一個包的包頭     
  141.                 index  =  headLengthIndex + length;     
  142.          
  143.             }else  
  144.             {     
  145.                 //假設包頭爲0表示沒有包了。那麼跳出循環     
  146.     
  147.                 break;     
  148.             }     
  149.         }     
  150.     }        
  151.          
  152.     //向服務端發送一條字符串     
  153.     //通常不會發送字符串 應該是發送數據包     
  154.     public void SendMessage(string str)     
  155.     {     
  156.         byte[] msg = Encoding.UTF8.GetBytes(str);     
  157.          
  158.         if(!clientSocket.Connected)     
  159.         {     
  160.             clientSocket.Close();     
  161.             return;     
  162.         }     
  163.         try  
  164.         {     
  165.             //int i = clientSocket.Send(msg);     
  166.             IAsyncResult asyncSend = clientSocket.BeginSend (msg,0,msg.Length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);     
  167.             bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );     
  168.             if ( !success )     
  169.             {     
  170.                 clientSocket.Close();     
  171.                 Debug.Log("Failed to SendMessage server.");     
  172.             }     
  173.         }     
  174.         catch  
  175.         {     
  176.              Debug.Log("send message error" );     
  177.         }     
  178.     }     
  179.          
  180.     //向服務端發送數據包,也就是一個結構體對象     
  181.     public void SendMessage(object obj)     
  182.     {     
  183.          
  184.         if(!clientSocket.Connected)     
  185.         {     
  186.             clientSocket.Close();     
  187.             return;     
  188.         }     
  189.         try  
  190.         {     
  191.             //先獲得數據包的長度     
  192.             short size = (short)Marshal.SizeOf(obj);     
  193.             //把數據包的長度寫入byte數組中     
  194.             byte [] head = BitConverter.GetBytes(size);     
  195.             //把結構體對象轉換成數據包,也就是字節數組     
  196.             byte[] data = StructToBytes(obj);     
  197.          
  198.             //此時就有了兩個字節數組。一個是標記數據包的長度字節數組, 一個是數據包字節數組,     
  199.             //同一時候把這兩個字節數組合併成一個字節數組     
  200.          
  201.             byte[] newByte = new byte[head.Length + data.Length];     
  202.             Array.Copy(head,0,newByte,0,head.Length);     
  203.             Array.Copy(data,0,newByte,head.Length, data.Length);     
  204.          
  205.             //計算出新的字節數組的長度     
  206.             int length = Marshal.SizeOf(size) + Marshal.SizeOf(obj);     
  207.          
  208.             //向服務端異步發送這個字節數組     
  209.             IAsyncResult asyncSend = clientSocket.BeginSend (newByte,0,length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);     
  210.             //監測超時     
  211.             bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );     
  212.             if ( !success )     
  213.             {     
  214.                 clientSocket.Close();     
  215.                 Debug.Log("Time Out !");     
  216.             }      
  217.          
  218.         }     
  219.         catch (Exception e)     
  220.         {     
  221.              Debug.Log("send message error: " + e );     
  222.         }     
  223.     }     
  224.          
  225.     //結構體轉字節數組     
  226.     public byte[] StructToBytes(object structObj)     
  227.     {     
  228.          
  229.         int size = Marshal.SizeOf(structObj);     
  230.         IntPtr buffer =  Marshal.AllocHGlobal(size);     
  231.         try  
  232.         {     
  233.             Marshal.StructureToPtr(structObj,buffer,false);     
  234.             byte[]  bytes  =   new byte[size];     
  235.             Marshal.Copy(buffer, bytes,0,size);     
  236.             return   bytes;     
  237.         }     
  238.         finally  
  239.         {     
  240.             Marshal.FreeHGlobal(buffer);     
  241.         }     
  242.     }     
  243.     //字節數組轉結構體     
  244.     public object BytesToStruct(byte[] bytes,   Type   strcutType)     
  245.     {     
  246.         int size = Marshal.SizeOf(strcutType);     
  247.         IntPtr buffer = Marshal.AllocHGlobal(size);     
  248.         try  
  249.         {     
  250.             Marshal.Copy(bytes,0,buffer,size);     
  251.             return  Marshal.PtrToStructure(buffer,   strcutType);     
  252.         }     
  253.         finally  
  254.         {     
  255.             Marshal.FreeHGlobal(buffer);     
  256.         }        
  257.          
  258.     }     
  259.          
  260.     private void sendCallback (IAsyncResult asyncSend)     
  261.     {     
  262.          
  263.     }     
  264.          
  265.     //關閉Socket     
  266.     public void Closed()     
  267.     {     
  268.          
  269.         if(clientSocket != null && clientSocket.Connected)     
  270.         {     
  271.             clientSocket.Shutdown(SocketShutdown.Both);     
  272.             clientSocket.Close();     
  273.         }     
  274.         clientSocket = null;     
  275.     }     
  276.          
  277. }  

爲了與服務端達成默契,推斷數據包是否完畢。咱們需要在數據包中定義包頭 。包頭一般是這個數據包的長度,也就是結構體對象的長度。正如代碼中咱們把兩個數據類型 short 和 object 合併成一個新的字節數組。socket

而後是數據包結構體的定義。需要注意假設你在作IOS和Android的話數據包中不要包括數組,否則在結構體轉換byte數組的時候會出錯。async

Marshal.StructureToPtr () error : Attempting to JIT compile method

JFPackage.cs

  1. using UnityEngine;     
  2. using System.Collections;     
  3. using System.Runtime.InteropServices;     
  4.          
  5. public class JFPackage     
  6. {     
  7.     //結構體序列化     
  8.     [System.Serializable]     
  9.     //4字節對齊 iphone 和 android上可以1字節對齊     
  10.     [StructLayout(LayoutKind.Sequential, Pack = 4)]     
  11.     public struct WorldPackage     
  12.     {     
  13.          public byte mEquipID;     
  14.          public byte mAnimationID;     
  15.          public byte mHP;     
  16.          public short mPosx;     
  17.          public short mPosy;     
  18.          public short mPosz;     
  19.          public short mRosx;     
  20.          public short mRosy;     
  21.          public short mRosz;     
  22.          
  23.          public WorldPackage(short posx,short posy,short posz, short rosx, short rosy, short rosz,byte equipID,byte animationID,byte hp)     
  24.          {     
  25.             mPosx = posx;     
  26.             mPosy = posy;     
  27.             mPosz = posz;     
  28.             mRosx = rosx;     
  29.             mRosy = rosy;     
  30.             mRosz = rosz;     
  31.             mEquipID = equipID;     
  32.             mAnimationID = animationID;     
  33.             mHP = hp;     
  34.          }     
  35.          
  36.     };       
  37.          
  38. }  

在腳本中運行發送數據包的動做,在Start方法中獲得Socket對象。

  1. public JFSocket mJFsorket;     
  2.          
  3. void Start ()     
  4. {     
  5.     mJFsorket = JFSocket.GetInstance();     
  6. }  

讓角色發生移動的時候。調用該方法向服務端發送數據。

  1. void SendPlayerWorldMessage()     
  2. {     
  3.                 //組成新的結構體對象,包含主角座標旋轉等。     
  4.      Vector3 PlayerTransform = transform.localPosition;     
  5.      Vector3 PlayerRotation = transform.localRotation.eulerAngles;     
  6.                 //用short的話是2字節。爲了節省包的長度。這裏乘以100 避免使用float 4字節。

    當server接受到的時候小數點向前移動兩位就是真實的float數據     

  7.      short px =  (short)(PlayerTransform.x*100);     
  8.      short py =  (short)(PlayerTransform.y*100);     
  9.      short pz =  (short)(PlayerTransform.z*100);     
  10.      short rx =  (short)(PlayerRotation.x*100);     
  11.      short ry =  (short)(PlayerRotation.y*100);     
  12.      short rz =  (short)(PlayerRotation.z*100);     
  13.      byte equipID = 1;     
  14.      byte animationID =9;     
  15.      byte hp = 2;     
  16.      JFPackage.WorldPackage wordPackage = new JFPackage.WorldPackage(px,py,pz,rx,ry,rz,equipID,animationID,hp);     
  17.                 //經過Socket發送結構體對象     
  18.      mJFsorket.SendMessage(wordPackage);     
  19. }  

接着就是client同步server的數據,眼下是測試階段因此寫的比較簡陋,只是原理都是同樣的。

哇咔咔!!

  1. //上次同步時間     
  2.       private float mSynchronous;     
  3.          
  4. void Update ()     
  5. {     
  6.          
  7.     mSynchronous +=Time.deltaTime;     
  8.     //在Update中每0.5s的時候同步一次     
  9.     if(mSynchronous > 0.5f)     
  10.     {     
  11.         int count = mJFsorket.worldpackage.Count;     
  12.         //當接受到的數據包長度大於0 開始同步     
  13.         if(count > 0)     
  14.         {     
  15.                                //遍歷數據包中 每個點的座標     
  16.             foreach(JFPackage.WorldPackage wp in mJFsorket.worldpackage)     
  17.             {     
  18.                 float x = (float)(wp.mPosx / 100.0f);     
  19.                 float y = (float)(wp.mPosy /100.0f);     
  20.                 float z = (float)(wp.mPosz /100.0f);     
  21.          
  22.                 Debug.Log("x = " + x + " y = " + y+" z = " + z);     
  23.                   //同步主角的新座標     
  24.                 mPlayer.transform.position = new Vector3 (x,y,z);     
  25.             }     
  26.                                //清空數據包鏈表     
  27.             mJFsorket.worldpackage.Clear();     
  28.         }     
  29.         mSynchronous = 0;     
  30.     }     
  31. }  

主角移動的同一時候。經過Socket時時同步座標喔。。

有沒有感受這個牛頭人很帥氣 哈哈哈。

對於Socket的使用,我相信沒有比MSDN更加具體的了。

有關Socket 同步請求異步請求的地方可以參照MSDN  連接地址給出來了,好好學習吧,嘿嘿。 msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.aspx

上述代碼中我使用的是Thread() 沒有使用協同任務StartCoroutine() 。緣由是協同任務必需要繼承MonoBehaviour,並且該腳本要綁定在遊戲對象身上。問題綁定在遊戲對象身上切換場景的時候這個腳本一定會釋放,那麼Socket確定會斷開鏈接。因此我需要用Thread,並且協同任務它並不是嚴格意義上的多線程。

2.HTTP

HTTP請求在Unity我相信用的會更少一些,因爲HTTP會比SOCKET慢很是多,因爲它每次請求完都會斷開。廢話不說了, 我用HTTP請求製做用戶的登陸。

用HTTP請求直接使用Unity自帶的www類就可以,因爲HTTP請求僅僅有登陸纔會有, 因此我就在腳本中來完畢, 使用 www 類 和 協同任務StartCoroutine()。

  1. using UnityEngine;     
  2. using System.Collections;     
  3. using System.Collections.Generic;     
  4. public class LoginGlobe : MonoBehaviour {     
  5.          
  6.     void Start ()     
  7.     {     
  8.         //GET請求     
  9.         StartCoroutine(GET("http://xuanyusong.com/"));     
  10.          
  11.     }     
  12.          
  13.     void Update ()     
  14.     {     
  15.          
  16.     }     
  17.          
  18.     void OnGUI()     
  19.     {     
  20.          
  21.     }     
  22.          
  23.     //登陸     
  24.     public void LoginPressed()     
  25.     {     
  26.         //登陸請求 POST 把參數寫在字典用 經過www類來請求     
  27.         Dictionary<string,string> dic = new Dictionary<stringstring> ();     
  28.         //參數     
  29.         dic.Add("action","0");     
  30.         dic.Add("usrname","xys");     
  31.         dic.Add("psw","123456");     
  32.          
  33.         StartCoroutine(POST("http://192.168.1.12/login.php",dic));     
  34.          
  35.     }     
  36.     //註冊     
  37.     public void SingInPressed()     
  38.     {     
  39.         //註冊請求 POST     
  40.         Dictionary<string,string> dic = new Dictionary<stringstring> ();     
  41.         dic.Add("action","1");     
  42.         dic.Add("usrname","xys");     
  43.         dic.Add("psw","123456");     
  44.          
  45.         StartCoroutine(POST("http://192.168.1.12/login.php",dic));     
  46.     }     
  47.          
  48.     //POST請求     
  49.     IEnumerator POST(string url, Dictionary<string,string> post)     
  50.     {     
  51.         WWWForm form = new WWWForm();     
  52.         foreach(KeyValuePair<string,string> post_arg in post)     
  53.         {     
  54.             form.AddField(post_arg.Key, post_arg.Value);     
  55.         }     
  56.          
  57.         WWW www = new WWW(url, form);     
  58.         yield return www;     
  59.          
  60.         if (www.error != null)     
  61.         {     
  62.             //POST請求失敗     
  63.             Debug.Log("error is :"+ www.error);     
  64.          
  65.         } else  
  66.         {     
  67.             //POST請求成功     
  68.              Debug.Log("request ok : " + www.text);     
  69.         }     
  70.     }     
  71.          
  72.     //GET請求     
  73.     IEnumerator GET(string url)     
  74.     {     
  75.          
  76.         WWW www = new WWW (url);     
  77.         yield return www;     
  78.          
  79.         if (www.error != null)     
  80.         {     
  81.             //GET請求失敗     
  82.             Debug.Log("error is :"+ www.error);     
  83.          
  84.         } else  
  85.         {     
  86.             //GET請求成功     
  87.              Debug.Log("request ok : " + www.text);     
  88.         }     
  89.     }     
  90.          
  91. }  

假設想經過HTTP傳遞二進制流的話 可以使用 如下的方法。

  1. WWWForm wwwForm = new WWWForm();     
  2.          
  3.      byte[] byteStream = System.Text.Encoding.Default.GetBytes(stream);     
  4.          
  5.      wwwForm.AddBinaryData("post", byteStream);     
  6.          
  7.      www = new WWW(Address, wwwForm);  

眼下Socket數據包仍是沒有進行加密算法。後期我會補上。

歡迎討論。互相學習互相進度 加油,蛤蛤。

下載地址我不貼了。因爲沒有服務端的東西 執行也看不到效果。

但願你們學習愉快, 咱們下次再見!

相關文章
相關標籤/搜索