1.Socket
Socket不要写在脚本上,如果写在脚本上游戏场景一旦切换,那么这条脚本会被释放掉,Socket会断开连接。场景切换完毕后需要重新在与服务器建立Socket连接,这样会很麻烦。所以我们需要把Socket写在一个单例的类中,不用继承MonoBehaviour。这个例子我模拟一下,主角在游戏中移动,时时向服务端发送当前坐标,当服务器返回同步坐标时角色开始同步服务端新角色坐标。
Socket在发送消息的时候采用的是字节数组,也就是说无论你的数据是 int float short object 都会将这些数据类型先转换成byte[] , 目前在处理发送的地方我使用的是数据包,也就是把(角色坐标)结构体object转换成byte[]发送, 这就牵扯一个问题, 如何把结构体转成字节数组, 如何把字节数组回转成结构体。请大家接续阅读,答案就在后面,哇咔咔。
直接上代码
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 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();
- 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 合并成一个新的字节数组。
然后是数据包结构体的定义,需要注意如果你在做iOS和Android的话数据包中不要包含数组,不然在结构体转换byte数组的时候会出错。
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);
- }
接着就是客户端同步服务器的数据,目前是测试阶段所以写的比较简陋,不过原理都是一样的。哇咔咔!!
-
- 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 链接地址给出来了,好好学习吧,嘿嘿。 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()。
- 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数据包还是没有进行加密算法,后期我会补上。欢迎讨论,互相学习互相进度 加油,蛤蛤。
下载地址我不贴了,因为没有服务端的东西 运行也看不到效果。 希望大家学习愉快, 我们下次再见!
2013-10-13 11:08
5029人阅读
收藏
举报
最近比较忙,有段时间没写博客拉。最近项目中需要使用HTTP与Socket,雨松MOMO把自己这段时间学习的资料整理一下。有关Socket与HTTP的基础知识MOMO就不赘述拉,不懂得朋友自己谷歌吧。我们项目的需求是在登录的时候使用HTTP请求,游戏中其它的请求都用Socket请求,比如人物移动同步坐标,同步关卡等等。
1.Socket
Socket不要写在脚本上,如果写在脚本上游戏场景一旦切换,那么这条脚本会被释放掉,Socket会断开连接。场景切换完毕后需要重新在与服务器建立Socket连接,这样会很麻烦。所以我们需要把Socket写在一个单例的类中,不用继承MonoBehaviour。这个例子我模拟一下,主角在游戏中移动,时时向服务端发送当前坐标,当服务器返回同步坐标时角色开始同步服务端新角色坐标。
Socket在发送消息的时候采用的是字节数组,也就是说无论你的数据是 int float short object 都会将这些数据类型先转换成byte[] , 目前在处理发送的地方我使用的是数据包,也就是把(角色坐标)结构体object转换成byte[]发送, 这就牵扯一个问题, 如何把结构体转成字节数组, 如何把字节数组回转成结构体。请大家接续阅读,答案就在后面,哇咔咔。
直接上代码
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 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();
- 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 合并成一个新的字节数组。
然后是数据包结构体的定义,需要注意如果你在做iOS和Android的话数据包中不要包含数组,不然在结构体转换byte数组的时候会出错。
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);
- }
接着就是客户端同步服务器的数据,目前是测试阶段所以写的比较简陋,不过原理都是一样的。哇咔咔!!
-
- 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 链接地址给出来了,好好学习吧,嘿嘿。 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()。
- 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数据包还是没有进行加密算法,后期我会补上。欢迎讨论,互相学习互相进度 加油,蛤蛤。
下载地址我不贴了,因为没有服务端的东西 运行也看不到效果。 希望大家学习愉快, 我们下次再见!