Warensoft Unity3D通信庫使用向導2-利用UnityHttpClient類實現Http通信


Warensoft Unity3D通信庫使用向導2-利用UnityHttpClient類實現Http通信

(作者:warensoft,有問題請聯系warensoft@163.com)

利用Warensoft.Unity.Communication.Client.UnityHttpClient類可以實現Http Get請求以及POST請求,並可以使用簡單的獲取本次請求所對對應的響應。可以使用該類完全代替內置的WWW類。

推薦使用UnityHttpClient替代WWW的原因有以下幾點:

               1>WWW類的使用不符合微軟命名規范

               2>大量並發使用WWW類時會拋出Too Many Threads的異常.UnityHttpClient已經在內部對並發線程數量進行了控制.

使用UnityHttpClient類,代碼更加簡潔

下面通過代碼展示如何使用UnityHttpClient類:

  1. 下載Warensoft Unity3D通信庫

    該類庫是Codeplex上的開源項目,地址是:http://wucl.codeplex.com,從上面下載類庫的最新版本,下載后得到兩個DLL文件,其中Warensoft.Unity.Communication.dll就是我們在本Demo中用的DLL文件,另外一個Warensoft.DataService.dll是數據服務庫,在后面的章節中會講解如何使用.

  2. 為了客戶端代碼能成功演示,下面在VisualStudio中建立一個網站,當做Http服務器,為了演示UnityHttpClient對文件的請求,需要在網站中添加一個名為Test.xml的XML文件,以及一個test.png的PNG圖,如下圖所示:

    Test.xml的內容如下所示:

 

<?xml version="1.0" encoding="utf-8" ?>

<Root>

<Customer>ALFKI</Customer>

</Root>

 

 

 

Test.png的圖片如下所示:

     3.為了演示通過Get方式請求數據,需要在網站中添加一個GetTest.aspx頁面,其對應的ASPX.CS中的代碼如下所示:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

 

public partial class GetTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//該代碼功能是通過查詢字符串CustomerID的值去查詢該客戶對應的公司名,

//並將查找到的公司返回給客戶端

string customerid = this.Request.QueryString["CustomerID"];

if (customerid!=null )

{

string companyName = "";

using (SqlConnection con=new SqlConnection ("server=.;database=northwind;uid=sa;pwd=sa"))

{

var cmd = con.CreateCommand();

cmd.CommandText = "select companyname from customers where customerid=@customerid";

cmd.Parameters.AddWithValue("@customerid",customerid);

con.Open();

var result = cmd.ExecuteScalar();

if (result !=null )

{

companyName = result.ToString();

}

}

this.Response.Write(companyName);

this.Response.End();

}

}

}

 

 

 

      4.為了演示通過POST方式發送數據,添加一個PostTest.aspx,其對應的CS文件代碼如下所示:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

 

public partial class PostTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//該代碼功能是通過獲取客戶端以Post方式發送的CustomerID的值去查詢該客戶//對應的公司名,並將查找到的公司返回給客戶端

if (this.Request .ContentLength!=0)

{

//獲取POST的數據流

var strm = this.Request.InputStream;

//建立緩沖區

byte[]buffer=new byte[this.Request .ContentLength];

//將POST過來的數據讀取出來,並且存儲在buffer中

strm.Read(buffer,0,buffer .Length );

//將二進制數據轉化為字符串

string customerid = System.Text.Encoding.UTF8.GetString(buffer);

string companyName = "";

using (SqlConnection con = new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa"))

{

var cmd = con.CreateCommand();

cmd.CommandText = "select companyname from customers where customerid=@customerid";

cmd.Parameters.AddWithValue("@customerid", customerid);

con.Open();

var result = cmd.ExecuteScalar();

if (result != null)

{

companyName = result.ToString();

}

}

this.Response.Write(companyName);

this.Response.End();

}

}

}

 

 

      5.在Unity3D中建立一個新的項目,建立一個文件夾改名為Plugins,並將Warensoft.Unity.Communication.dll拷貝到該文件夾下面,如下圖所示:

      6.在Project中添加一個CS腳本,並將其命名為HttpTest.cs,其代碼如下所示:

 

using UnityEngine;

using System.Collections;

using Warensoft.Unity.Communication.Client;

using System;

using System.Xml;

 

public class HttpTest : MonoBehaviour {

 

UnityHttpClient httpClient = null;

private Texture2D image;

    void Start () {

      

//啟動時將httpClient初始化

this.httpClient = UnityCommunicationManager.CreateInstance().GetHttpClient();

this.httpClient.Error += new EventHandler<HttpRequestErrorEventArgs>(httpClient_Error);

    }

 

void httpClient_Error(object sender, HttpRequestErrorEventArgs e)

{

print(e.ResponseText );

}

int initStep = 0;

    void Update () {

if (this.initStep ==0&&this.httpClient!=null )

{

 

//獲取XML文件

this.httpClient.BeginGetHttpContent("http://localhost:17737/test11/test.xml",

//后面的方法是本次異步Http請求成功並響應后的回調方法

new Action<XmlDocument>((doc) =>

{

//打印XML文件

print("response xml content:");

print(doc.OuterXml);

}));

//獲取圖片

this.httpClient.BeginGetHttpContent("http://localhost:17737/test11/test.png",

//后面的方法是本次異步Http請求成功並響應后的回調方法

new Action<Texture2D>((img) =>

{

this.image = img;

}));

//獲取純文本

//通過客戶ID查詢公司名

//GET方式

this.httpClient.BeginGetHttpContent("http://localhost:17737/test11/GetTest.aspx?CustomerID=ALFKI",

//后面的方法是本次異步Http請求成功並響應后的回調方法

new Action<string>((stringResult) =>

{

//打印公司名

print("Get the company name of alfki:" + stringResult);

}));

//獲取純文本

//通過客戶ID查詢公司名

//POST方式

byte[] contentBuffer = System.Text.Encoding.UTF8.GetBytes("ALFKI");

this.httpClient.BeginPost("http://localhost:17737/test11/PostTest.aspx", contentBuffer,

(response) =>

{

//打印公司名

print("Post the company name of alfki:" + response.StringContent);

});

this.initStep = 1;

}

 

    }

void OnGUI()

{

if (this.image !=null )

{

GUI.DrawTexture(new Rect (0,0,this.image .width,this.image.height),this.image);

}

}

}

 

 

 

    7.將該cs文件拖放到該場景的主攝像機上,如下圖所示:

       8.保存項目並運行

          游戲視圖輸出如下圖所示:

        控制台輸出內容如下圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM