在Unityd3d,与后端交互比较多的是Http协议,Socket套接字;
HTTP协议:Unity的 WWW 就是基于HTTP协议的网络传输功能,HTTP协议即超文本协议,HTTP协议的一个重要特点就是每次连接只处理一个请求,当服务器处理完客户端的请求后即断开连接,节省传输时间(适合用作短连接)
在Unity中,WWW主要支持其中的GET和POST方式。GET方式会请求附加在URL后,POST方式是通过FORM(表单)的形式提交。GET方式最多只能传输1024个字节,POST方式理论上没有限制。(实际使用POST方式比较多)
//WWW中的GET方式
IEnumerator IGetDate()
{
WWW www = new WWW("http://127.0.0.1/test.php?username=get&password=12345");
yield return www;
string m_info = String.Empty;
if (www.error != null)
{
m_info = www.error;
yield return null;
}
m_info = www.text;
}
向指定的IP地址(http://127.0.0.1/test.php)发送GET请求,“?”后面用于附加数据,发送两个GET数据,一个是username:get,一个是password:123456,WWW实例会在后台运行,yield return www 等待Web服务器的反应,返回的数据会保存在www.text中
//POST请求
IEnumerator IPostData()
{
System.Collections.Hashtable headers = new System.Collections.Hashtable();
headers.Add("Content-Type","application/x-www-form-urlencoded");
string data = "username=post&password=123456";
bytes bs = System.Text.UTF8Encoding.UTF8.Getbytes(data);
WWW www = new WWW("http://127.0.0.1/test.php",bs,headers);
yield return www;
string m_info = string.Empty;
if (www.error != null)
{
m_info = www.error;
yield return null;
}
m_info = www.text;
}
headers是一个Hashtable,由建,值对应,这里用它来保存HTTP报头,保存数据的字符串中,仍用“&”符号连接数据
通过.net提供的Socket功能实现基于TCP/IP协议的网络通讯(一般游戏都采用这个):
www可以用于动态请求,但是,无法满足实时交互的网络需求,这个时候就需要建立长连接,Socket套接字之间的连接过程分三个步骤:服务器监听,客户端请求,连接确认,这里只做客户端的请求:
public class StateObject
{
private const int BUFFER_SIZE = 327680;
private Socket worker;
private static byte[] buffer = new byte[BUFFER_SIZE];
public StateObject(Socket worker)
{
this.worker = worker; //保存服务器Socket对象
}
//用来接收数据返回的Socket对象
public Socket Worker
{
get {return this.worker;}
set {this.worker = value;}
}
//用来接收服务端返回的数据
public byte[] Buffer
{
get{return buffer;}
set{buffer = value;}
}
public int bufferSize
{
get {return BUFFER_SIZE;}
}
}
//建立Socket 连接
public bool Connect(string address, int remotePort)
{
try
{
IPAddress[] ips = Dns.GetHostAddresses(address); //解析域名
IPEndPoint remoteEP = new IPEndPoint(ips[0],port); //获得远程服务器的地址
Socket client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //创建Socket
client.BeginConnect(remoteEP,new AsyncCallback(OnConnectCallback),client); //开启异步连接
}
catch (System.Exception e)
{
Debug.Log("Connect fail! : " + e);
return false;
}
return true;
}
//连接操作完成调用回调
private void OnConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState; //获得服务器Socket
client.EndConnect(ar); //与服务器取得连接
cnn = client; //保存服务器Socket
Receive(); //接收服务器发送过来的数据
}
catch(System.Exception e)
{
Debug.Log("OnConnectCallback fail! : " + e);
}
}
//接收服务端发送过来的数据
public void Recive()
{
try
{
StateObject so = new StateOject(cnn); //定义一个StateObject类,用来保存服务器Socket对象,以及服务器传过来的数据
so.Worker.BeginReceive(so.buffer,0,so.BufferSize,0,new AsyncCallback(OnReceiveCallBack),so);
}
cahch(System.Exception e)
{
Debug.Log("Recive:" + e);
}
}
//调用接收成功的返回回调
private void OnReceiveCallBack(IAsyncResult ar)
{
try
{
StateObject so = (StateObject)ar.AsyncState;
int bytesRead = so.Worker.EndReceive(ar); //结束异步读取,返回接收到的字节数
if (bytesRead < 1) //接收字节为0,与服务器断开连接
{
ClioseSocket();
return;
}
//这里可以进行解析数据包
}
catch(System.Exception e)
{
Debug.Log("OnReceiveback: " + e);
}
}
//发送数据包字节
protected bool Send(byte[] buffer)
{
try
{
Socket client = cnn; //这里cnn为之前建立连接之后保存的服务器Socket对象
client.BeginSend(buffer,0,buffer.Length,SocketFlags.None,new AsyncCallback(OnSendCallBack),client);
}
catch(System.Exception e)
{
Debug.Log("Send : " + e);
}
}
//调用发送回调
private void OnSendCallBack(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesWritten = client.EndSend(ar);
}
catch(System.Exception e)
{
Debug.Log("SendCallBack : " + e);
}
}
//关闭Socket连接
public void Close()
{
try
{
Socket client = cnn;
client.Shutdown(SocketShutdown.Both);
client.BeginDisconnet(false,new AsyncCallback(OnCloseCallBack),client);
}
catch(System.Exception e)
{
Debug.Log("close : " + e);
}
}
private void OnCloseCallBack(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndDisconnet(ar);
client.Close();
}
}
转载自 https://blog.csdn.net/icrazyaaa/article/details/49909937