<轉>Unity3D研究院之C#使用Socket與HTTP鏈接服務器傳輸數據包

最近項目中須要使用HTTP與Socket,把本身這段時間學習的資料整理一下。有關Socket與HTTP的基礎知識MOMO就不贅述拉,不懂得朋友本身谷歌吧。咱們項目的需求是在登陸的時候使用HTTP請求,遊戲中其它的請求都用Socket請求,好比人物移動同步座標,同步關卡等等。php

1.Socketandroid

         Socket不要寫在腳本上,若是寫在腳本上游戲場景一旦切換,那麼這條腳本會被釋放掉,Socket會斷開鏈接。場景切換完畢後須要從新在與服務器創建Socket鏈接,這樣會很麻煩。因此咱們須要把Socket寫在一個單例的類中,不用繼承MonoBehaviour。這個例子我模擬一下,主角在遊戲中移動,時時向服務端發送當前座標,當服務器返回同步座標時角色開始同步服務端新角色座標。算法

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

直接上代碼服務器

JFSocket.cs 該單例類不要綁定在任何對象上數據結構

 

[代碼]:

[js] view plain copy
 
  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.     //在與服務器交互的時候會傳遞這個結構體  
  21.     //當客戶端接到到服務器返回的數據包時,我把結構體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.         //服務器IP地址  
  40.         IPAddress ipAddress = IPAddress.Parse ("192.168.1.100");  
  41.         //服務器端口  
  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.         //在這個線程中接受服務器返回的數據  
  70.         while (true)  
  71.         {   
  72.   
  73.             if(!clientSocket.Connected)  
  74.             {  
  75.                 //與服務器斷開鏈接跳出循環  
  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.                 break;  
  147.             }  
  148.         }  
  149.     }     
  150.   
  151.     //向服務端發送一條字符串  
  152.     //通常不會發送字符串 應該是發送數據包  
  153.     public void SendMessage(string str)  
  154.     {  
  155.         byte[] msg = Encoding.UTF8.GetBytes(str);  
  156.   
  157.         if(!clientSocket.Connected)  
  158.         {  
  159.             clientSocket.Close();  
  160.             return;  
  161.         }  
  162.         try  
  163.         {  
  164.             //int i = clientSocket.Send(msg);  
  165.             IAsyncResult asyncSend = clientSocket.BeginSend (msg,0,msg.Length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);  
  166.             bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );  
  167.             if ( !success )  
  168.             {  
  169.                 clientSocket.Close();  
  170.                 Debug.Log("Failed to SendMessage server.");  
  171.             }  
  172.         }  
  173.         catch  
  174.         {  
  175.              Debug.Log("send message error" );  
  176.         }  
  177.     }  
  178.   
  179.     //向服務端發送數據包,也就是一個結構體對象  
  180.     public void SendMessage(object obj)  
  181.     {  
  182.   
  183.         if(!clientSocket.Connected)  
  184.         {  
  185.             clientSocket.Close();  
  186.             return;  
  187.         }  
  188.         try  
  189.         {  
  190.             //先獲得數據包的長度  
  191.             short size = (short)Marshal.SizeOf(obj);  
  192.             //把數據包的長度寫入byte數組中  
  193.             byte [] head = BitConverter.GetBytes(size);  
  194.             //把結構體對象轉換成數據包,也就是字節數組  
  195.             byte[] data = StructToBytes(obj);  
  196.   
  197.             //此時就有了兩個字節數組,一個是標記數據包的長度字節數組, 一個是數據包字節數組,  
  198.             //同時把這兩個字節數組合併成一個字節數組  
  199.   
  200.             byte[] newByte = new byte[head.Length + data.Length];  
  201.             Array.Copy(head,0,newByte,0,head.Length);  
  202.             Array.Copy(data,0,newByte,head.Length, data.Length);  
  203.   
  204.             //計算出新的字節數組的長度  
  205.             int length = Marshal.SizeOf(size) + Marshal.SizeOf(obj);  
  206.   
  207.             //向服務端異步發送這個字節數組  
  208.             IAsyncResult asyncSend = clientSocket.BeginSend (newByte,0,length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);  
  209.             //監測超時  
  210.             bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );  
  211.             if ( !success )  
  212.             {  
  213.                 clientSocket.Close();  
  214.                 Debug.Log("Time Out !");  
  215.             }   
  216.   
  217.         }  
  218.         catch (Exception e)  
  219.         {  
  220.              Debug.Log("send message error: " + e );  
  221.         }  
  222.     }  
  223.   
  224.     //結構體轉字節數組  
  225.     public byte[] StructToBytes(object structObj)  
  226.     {  
  227.   
  228.         int size = Marshal.SizeOf(structObj);  
  229.         IntPtr buffer =  Marshal.AllocHGlobal(size);  
  230.         try  
  231.         {  
  232.             Marshal.StructureToPtr(structObj,buffer,false);  
  233.             byte[]  bytes  =   new byte[size];  
  234.             Marshal.Copy(buffer, bytes,0,size);  
  235.             return   bytes;  
  236.         }  
  237.         finally  
  238.         {  
  239.             Marshal.FreeHGlobal(buffer);  
  240.         }  
  241.     }  
  242.     //字節數組轉結構體  
  243.     public object BytesToStruct(byte[] bytes,   Type   strcutType)  
  244.     {  
  245.         int size = Marshal.SizeOf(strcutType);  
  246.         IntPtr buffer = Marshal.AllocHGlobal(size);  
  247.         try  
  248.         {  
  249.             Marshal.Copy(bytes,0,buffer,size);  
  250.             return  Marshal.PtrToStructure(buffer,   strcutType);  
  251.         }  
  252.         finally  
  253.         {  
  254.             Marshal.FreeHGlobal(buffer);  
  255.         }     
  256.   
  257.     }  
  258.   
  259.     private void sendCallback (IAsyncResult asyncSend)  
  260.     {  
  261.   
  262.     }  
  263.   
  264.     //關閉Socket  
  265.     public void Closed()  
  266.     {  
  267.   
  268.         if(clientSocket != null && clientSocket.Connected)  
  269.         {  
  270.             clientSocket.Shutdown(SocketShutdown.Both);  
  271.             clientSocket.Close();  
  272.         }  
  273.         clientSocket = null;  
  274.     }  
  275.   
  276. }  

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

 

而後是數據包結構體的定義,須要注意若是你在作iOSAndroid的話數據包中不要包含數組,否則在結構體轉換byte數組的時候會出錯。iphone

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

 

JFPackage.cssocket

 

[代碼]:

[js] view plain copy
 
  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對象。

 

 

[代碼]:

[js] view plain copy
 
  1. public JFSocket mJFsorket;  
  2.   
  3. void Start ()  
  4. {  
  5.     mJFsorket = JFSocket.GetInstance();  
  6. }  

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

 

 

[代碼]:

[js] view plain copy
 
  1. void SendPlayerWorldMessage()  
  2. {  
  3.                 //組成新的結構體對象,包括主角座標旋轉等。  
  4.      Vector3 PlayerTransform = transform.localPosition;  
  5.      Vector3 PlayerRotation = transform.localRotation.eulerAngles;  
  6.                 //用short的話是2字節,爲了節省包的長度。這裏乘以100 避免使用float 4字節。當服務器接受到的時候小數點向前移動兩位就是真實的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. }  

接着就是客戶端同步服務器的數據,目前是測試階段因此寫的比較簡陋,不過原理都是同樣的。

 

 

[代碼]:

[js] view plain copy
 
  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  連接地址給出來了,好好學習吧,嘿嘿。 http://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()。

 

[代碼]:

[js] view plain copy
 
  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<string, string> ();  
  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<string, string> ();  
  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數據包仍是沒有進行加密算法,後期我會補上。歡迎討論,互相學習互相進度 加油,蛤蛤。

下載地址我不貼了,由於沒有服務端的東西 運行也看不到效果。

相關文章
相關標籤/搜索