近期比較忙。有段時間沒寫博客拉。近期項目中需要使用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 該單例類不要綁定在不論什麼對象上異步
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Collections.Generic;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
-
- public class JFSocket
- {
-
-
- private Socket clientSocket;
-
-
-
- public List<JFPackage.WorldPackage> worldpackage;
-
- private static JFSocket instance;
- public static JFSocket GetInstance()
- {
- if (instance == null)
- {
- instance = new JFSocket();
- }
- return instance;
- }
-
-
- JFSocket()
- {
-
- clientSocket = new Socket (AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
-
- IPAddress ipAddress = IPAddress.Parse ("192.168.1.100");
-
- IPEndPoint ipEndpoint = new IPEndPoint (ipAddress, 10060);
-
- IAsyncResult result = clientSocket.BeginConnect (ipEndpoint,new AsyncCallback (connectCallback),clientSocket);
-
- bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
- if ( !success )
- {
-
- Closed();
- Debug.Log("connect Time Out");
- }else
- {
-
- worldpackage = new List<JFPackage.WorldPackage>();
- Thread thread = new Thread(new ThreadStart(ReceiveSorket));
- thread.IsBackground = true;
- thread.Start();
- }
- }
-
- private void connectCallback(IAsyncResult asyncConnect)
- {
- Debug.Log("connectSuccess");
- }
-
- private void ReceiveSorket()
- {
-
- while (true)
- {
-
- if(!clientSocket.Connected)
- {
-
- Debug.Log("Failed to clientSocket server.");
- clientSocket.Close();
- break;
- }
- try
- {
-
- byte[] bytes = new byte[4096];
-
-
- int i = clientSocket.Receive(bytes);
- if(i <= 0)
- {
- clientSocket.Close();
- break;
- }
-
-
-
-
- if(bytes.Length > 2)
- {
- SplitPackage(bytes,0);
- }else
- {
- Debug.Log("length is not > 2");
- }
-
- }
- catch (Exception e)
- {
- Debug.Log("Failed to clientSocket error." + e);
- clientSocket.Close();
- break;
- }
- }
- }
-
- private void SplitPackage(byte[] bytes , int index)
- {
-
-
- while(true)
- {
-
- byte[] head = new byte[2];
- int headLengthIndex = index + 2;
-
- Array.Copy(bytes,index,head,0,2);
-
- short length = BitConverter.ToInt16(head,0);
-
- if(length > 0)
- {
- byte[] data = new byte[length];
-
- Array.Copy(bytes,headLengthIndex,data,0,length);
-
-
-
- JFPackage.WorldPackage wp = new JFPackage.WorldPackage();
- wp = (JFPackage.WorldPackage)BytesToStruct(data,wp.GetType());
-
- worldpackage.Add(wp);
-
- index = headLengthIndex + length;
-
- }else
- {
-
-
- break;
- }
- }
- }
-
-
-
- public void SendMessage(string str)
- {
- byte[] msg = Encoding.UTF8.GetBytes(str);
-
- if(!clientSocket.Connected)
- {
- clientSocket.Close();
- return;
- }
- try
- {
-
- IAsyncResult asyncSend = clientSocket.BeginSend (msg,0,msg.Length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);
- bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );
- if ( !success )
- {
- clientSocket.Close();
- Debug.Log("Failed to SendMessage server.");
- }
- }
- catch
- {
- Debug.Log("send message error" );
- }
- }
-
-
- public void SendMessage(object obj)
- {
-
- if(!clientSocket.Connected)
- {
- clientSocket.Close();
- return;
- }
- try
- {
-
- short size = (short)Marshal.SizeOf(obj);
-
- byte [] head = BitConverter.GetBytes(size);
-
- byte[] data = StructToBytes(obj);
-
-
-
-
- byte[] newByte = new byte[head.Length + data.Length];
- Array.Copy(head,0,newByte,0,head.Length);
- Array.Copy(data,0,newByte,head.Length, data.Length);
-
-
- int length = Marshal.SizeOf(size) + Marshal.SizeOf(obj);
-
-
- IAsyncResult asyncSend = clientSocket.BeginSend (newByte,0,length,SocketFlags.None,new AsyncCallback (sendCallback),clientSocket);
-
- bool success = asyncSend.AsyncWaitHandle.WaitOne( 5000, true );
- if ( !success )
- {
- clientSocket.Close();
- Debug.Log("Time Out !");
- }
-
- }
- catch (Exception e)
- {
- Debug.Log("send message error: " + e );
- }
- }
-
-
- public byte[] StructToBytes(object structObj)
- {
-
- int size = Marshal.SizeOf(structObj);
- IntPtr buffer = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.StructureToPtr(structObj,buffer,false);
- byte[] bytes = new byte[size];
- Marshal.Copy(buffer, bytes,0,size);
- return bytes;
- }
- finally
- {
- Marshal.FreeHGlobal(buffer);
- }
- }
-
- public object BytesToStruct(byte[] bytes, Type strcutType)
- {
- int size = Marshal.SizeOf(strcutType);
- IntPtr buffer = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.Copy(bytes,0,buffer,size);
- return Marshal.PtrToStructure(buffer, strcutType);
- }
- finally
- {
- Marshal.FreeHGlobal(buffer);
- }
-
- }
-
- private void sendCallback (IAsyncResult asyncSend)
- {
-
- }
-
-
- public void Closed()
- {
-
- if(clientSocket != null && clientSocket.Connected)
- {
- clientSocket.Shutdown(SocketShutdown.Both);
- clientSocket.Close();
- }
- clientSocket = null;
- }
-
- }
爲了與服務端達成默契,推斷數據包是否完畢。咱們需要在數據包中定義包頭 。包頭一般是這個數據包的長度,也就是結構體對象的長度。正如代碼中咱們把兩個數據類型 short 和 object 合併成一個新的字節數組。socket
而後是數據包結構體的定義。需要注意假設你在作IOS和Android的話數據包中不要包括數組,否則在結構體轉換byte數組的時候會出錯。async
Marshal.StructureToPtr () error : Attempting to JIT compile method
JFPackage.cs
- using UnityEngine;
- using System.Collections;
- using System.Runtime.InteropServices;
-
- public class JFPackage
- {
-
- [System.Serializable]
-
- [StructLayout(LayoutKind.Sequential, Pack = 4)]
- public struct WorldPackage
- {
- public byte mEquipID;
- public byte mAnimationID;
- public byte mHP;
- public short mPosx;
- public short mPosy;
- public short mPosz;
- public short mRosx;
- public short mRosy;
- public short mRosz;
-
- public WorldPackage(short posx,short posy,short posz, short rosx, short rosy, short rosz,byte equipID,byte animationID,byte hp)
- {
- mPosx = posx;
- mPosy = posy;
- mPosz = posz;
- mRosx = rosx;
- mRosy = rosy;
- mRosz = rosz;
- mEquipID = equipID;
- mAnimationID = animationID;
- mHP = hp;
- }
-
- };
-
- }
在腳本中運行發送數據包的動做,在Start方法中獲得Socket對象。
- public JFSocket mJFsorket;
-
- void Start ()
- {
- mJFsorket = JFSocket.GetInstance();
- }
讓角色發生移動的時候。調用該方法向服務端發送數據。
- void SendPlayerWorldMessage()
- {
-
- Vector3 PlayerTransform = transform.localPosition;
- Vector3 PlayerRotation = transform.localRotation.eulerAngles;
-
- short px = (short)(PlayerTransform.x*100);
- short py = (short)(PlayerTransform.y*100);
- short pz = (short)(PlayerTransform.z*100);
- short rx = (short)(PlayerRotation.x*100);
- short ry = (short)(PlayerRotation.y*100);
- short rz = (short)(PlayerRotation.z*100);
- byte equipID = 1;
- byte animationID =9;
- byte hp = 2;
- JFPackage.WorldPackage wordPackage = new JFPackage.WorldPackage(px,py,pz,rx,ry,rz,equipID,animationID,hp);
-
- mJFsorket.SendMessage(wordPackage);
- }
接着就是client同步server的數據,眼下是測試階段因此寫的比較簡陋,只是原理都是同樣的。
哇咔咔!!
-
- private float mSynchronous;
-
- void Update ()
- {
-
- mSynchronous +=Time.deltaTime;
-
- if(mSynchronous > 0.5f)
- {
- int count = mJFsorket.worldpackage.Count;
-
- if(count > 0)
- {
-
- foreach(JFPackage.WorldPackage wp in mJFsorket.worldpackage)
- {
- float x = (float)(wp.mPosx / 100.0f);
- float y = (float)(wp.mPosy /100.0f);
- float z = (float)(wp.mPosz /100.0f);
-
- Debug.Log("x = " + x + " y = " + y+" z = " + z);
-
- mPlayer.transform.position = new Vector3 (x,y,z);
- }
-
- mJFsorket.worldpackage.Clear();
- }
- mSynchronous = 0;
- }
- }
主角移動的同一時候。經過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()。
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- public class LoginGlobe : MonoBehaviour {
-
- void Start ()
- {
-
- StartCoroutine(GET("http://xuanyusong.com/"));
-
- }
-
- void Update ()
- {
-
- }
-
- void OnGUI()
- {
-
- }
-
-
- public void LoginPressed()
- {
-
- Dictionary<string,string> dic = new Dictionary<string, string> ();
-
- dic.Add("action","0");
- dic.Add("usrname","xys");
- dic.Add("psw","123456");
-
- StartCoroutine(POST("http://192.168.1.12/login.php",dic));
-
- }
-
- public void SingInPressed()
- {
-
- Dictionary<string,string> dic = new Dictionary<string, string> ();
- dic.Add("action","1");
- dic.Add("usrname","xys");
- dic.Add("psw","123456");
-
- StartCoroutine(POST("http://192.168.1.12/login.php",dic));
- }
-
-
- IEnumerator POST(string url, Dictionary<string,string> post)
- {
- WWWForm form = new WWWForm();
- foreach(KeyValuePair<string,string> post_arg in post)
- {
- form.AddField(post_arg.Key, post_arg.Value);
- }
-
- WWW www = new WWW(url, form);
- yield return www;
-
- if (www.error != null)
- {
-
- Debug.Log("error is :"+ www.error);
-
- } else
- {
-
- Debug.Log("request ok : " + www.text);
- }
- }
-
-
- IEnumerator GET(string url)
- {
-
- WWW www = new WWW (url);
- yield return www;
-
- if (www.error != null)
- {
-
- Debug.Log("error is :"+ www.error);
-
- } else
- {
-
- Debug.Log("request ok : " + www.text);
- }
- }
-
- }
假設想經過HTTP傳遞二進制流的話 可以使用 如下的方法。
- WWWForm wwwForm = new WWWForm();
-
- byte[] byteStream = System.Text.Encoding.Default.GetBytes(stream);
-
- wwwForm.AddBinaryData("post", byteStream);
-
- www = new WWW(Address, wwwForm);
眼下Socket數據包仍是沒有進行加密算法。後期我會補上。
歡迎討論。互相學習互相進度 加油,蛤蛤。
下載地址我不貼了。因爲沒有服務端的東西 執行也看不到效果。
但願你們學習愉快, 咱們下次再見!