php作为unity的后端,Unity UnityWebRequest实现与后端的交互

一般我们与后端对接的时候会用到UnityWebRequest

这里简单使用这个与后端进行交互

这个是总类

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

using System;

using UnityEngine.Networking;

public enum EOPERATION

{

LOGIN = 0,//登录

REGISTER,//注册

COLLEGELIST, //学院

MAJORLIST, //专业

CLASSLIST,//班级

EXISTMAIL,//邮箱重复验证

EXISTNUMBER, //学号重复验证

GETPASSWORD,//忘记密码

ADDSCORE,//添加成绩

DownLoad,

}

public class CallBackUser

{

public bool success;

public string msg;

public User obj;

}

public class WebWork : MonoBehaviour

{

Dictionary> _handers = new Dictionary>();

private string filepath;

bool isStartDownload;

UnityWebRequest request;

//根据协议号获取地址后缀

Dictionary mURLs = new Dictionary{

{ EOPERATION.LOGIN,"webapi/login" },

{ EOPERATION.REGISTER,"webapi/register"},

{ EOPERATION.COLLEGELIST,"user/college/list_combo"},

{ EOPERATION.MAJORLIST,"user/major/list_combo"},

{ EOPERATION.CLASSLIST,"user/class/list_combo"},

{ EOPERATION.EXISTMAIL,"webapi/existemail"},

{ EOPERATION.EXISTNUMBER,"webapi/existnumber"},

{EOPERATION.GETPASSWORD, "webapi/forget_pass"},

{EOPERATION.ADDSCORE,"webapi/add_score"},

{EOPERATION.DownLoad,"" }

};

private string ipAddress = "http://192.168.40.153:8000/";

AccountHander accountHander = new AccountHander();

public object JsonConvert { get; private set; }

//在这里注册消息返回后分发处理

public void Init()

{

accountHander.RegisterMsg(_handers);

DontDestroyOnLoad(this);

}

///

/// 传输数据

///

///

///

public void SendPost(EOPERATION op, Dictionary dic)

{

//根据协议号获取完整路径

string url = ipAddress + mURLs[op];

StartCoroutine(Post(url, dic, op));

}

///

/// 获取数据

///

///

public void SendGet(EOPERATION op, string name = "")

{

string url = ipAddress + mURLs[op] + "/" + name;

StartCoroutine(Get(url, op, name));

}

///

/// 获取下载进度

///

///

public float GetProgress()

{

if (request == null || !isStartDownload)

return 0;

return request.downloadProgress;

}

private IEnumerator Get(string url, EOPERATION op, string name)

{

if (!string.IsNullOrEmpty(url))

{

using (request = UnityWebRequest.Get(url))

{

isStartDownload = true;

//设置超时 链接超时返回 且isNetworkError为true

request.timeout = 30;

yield return request.SendWebRequest();

isStartDownload = false;

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](name, request.downloadHandler);

}

};

}

}

//private WWW http;

private IEnumerator Post(string url, Dictionary dic, EOPERATION op)

{

if (!string.IsNullOrEmpty(url))

{

WWWForm form = new WWWForm();

foreach (var item in dic)

{

form.AddField(item.Key, item.Value);

}

using (request = UnityWebRequest.Post(url, form))

{

yield return request.SendWebRequest();

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](name, request.downloadHandler);

}

}

}

}

}

工具类

using System.IO;

public class FileTool

{

///

/// 创建文件

///

public static void CreateFile(string filePath,byte[]bytes)

{

using (FileStream fs = new FileStream(filePath,FileMode.Create,FileAccess.Write))

{

fs.Write(bytes, 0, bytes.Length);

}

}

}

消息返回处理类 这只是一个分类

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.Networking;

public class AccountHander

{

public void RegisterMsg(Dictionary> handers)

{

handers.Add(EOPERATION.LOGIN, OnRspLogin);

handers.Add(EOPERATION.REGISTER, OnRspRegister);

handers.Add(EOPERATION.DownLoad, OnRspDownLoad);

}

private void OnRspLogin(string name,DownloadHandler data)

{

//用Json转化为类内部数据

JsonConvert.DeserializeObject(data.text);

}

private void OnRspRegister(string name,DownloadHandler data)

{

}

private void OnRspDownLoad(string name,DownloadHandler data)

{

//data.data二进制的文件 视频 图片的信息

FileTool.CreateFile(name, data.data);

}

}

public void RegisterMsg(Dictionary> handers)

{

}

如果想添加一个新的就在主类Init里注册 然后新类写一个注册方法就行了 这样会自动根据枚举转到相应的处理函数

然后name的话只是为了区分下载文件起码要改名吧 不然不知道名字 如果只是传数据可以无视name不调用

来用一个demo使用下

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Text : MonoBehaviour {

WebWork we = new WebWork();

// Use this for initialization

void Start () {

we = transform.GetComponent();

we.Init();

we.SendGet(EOPERATION.DownLoad,"chuanjianyinwei.mp4");

}

// Update is called once per frame

void Update () {

Debug.Log(we.GetProgress());

}

}

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

打开exe开启一个临时资源服务器

记得设置端口号 把配置xml和要下载的文件放入

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

在主类把上面的地址粘贴过去

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

挂上脚本运行 进度条显示

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

资源服务器也有记录

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

打开项目文件夹也有

88d23ed1f410?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

改了一下分发器只用实现接口 会根据反射自动初始化实例类 这样不用写那么多初始化代码了

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

using System;

using UnityEngine.Networking;

using System.Reflection;

using System.Linq;

public enum EOPERATION

{

LOGIN = 0,//登录

REGISTER,//注册

COLLEGELIST, //学院

MAJORLIST, //专业

CLASSLIST,//班级

EXISTMAIL,//邮箱重复验证

EXISTNUMBER, //学号重复验证

GETPASSWORD,//忘记密码

ADDSCORE,//添加成绩

DownLoad,

}

public class CallBackUser

{

public bool success;

public string msg;

public User obj;

}

///

/// 分发器接口

///

public interface IHander

{

void RegisterMsg(Dictionary> handers);

};

public class WebWork : MonoBehaviour

{

Dictionary> _handers = new Dictionary>();

bool isStartDownload;

UnityWebRequest request;

//根据协议号获取地址后缀

Dictionary mURLs = new Dictionary{

{ EOPERATION.LOGIN,"webapi/login" },

{ EOPERATION.REGISTER,"webapi/register"},

{ EOPERATION.COLLEGELIST,"user/college/list_combo"},

{ EOPERATION.MAJORLIST,"user/major/list_combo"},

{ EOPERATION.CLASSLIST,"user/class/list_combo"},

{ EOPERATION.EXISTMAIL,"webapi/existemail"},

{ EOPERATION.EXISTNUMBER,"webapi/existnumber"},

{EOPERATION.GETPASSWORD, "webapi/forget_pass"},

{EOPERATION.ADDSCORE,"webapi/add_score"},

{EOPERATION.DownLoad,"" }

};

private string ipAddress = "http://192.168.40.153:8000/";

public object JsonConvert { get; private set; }

//在这里注册消息返回后分发处理

public void Init()

{

//返回我的解决方案中的所有程序集

Type[] types = AppDomain.CurrentDomain.GetAssemblies()

.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IHander))))

.ToArray();

//相当于

//public static IEnumerable GetType(Type interfaceType)

//{

// foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())

// {

// foreach (var type in assembly.GetTypes())

// {

// foreach (var t in type.GetInterfaces())

// {

// if (t == interfaceType)

// {

// yield return type;

// break;

// }

// }

// }

// }

//}

foreach (var item in types)

{

IHander obj = (IHander)Activator.CreateInstance(item);

obj.RegisterMsg(_handers);

}

DontDestroyOnLoad(this);

}

///

/// 传输数据

///

///

///

public void SendPost(EOPERATION op, Dictionary dic)

{

//根据协议号获取完整路径

string url = ipAddress + mURLs[op];

StartCoroutine(Post(url, dic, op));

}

///

/// 获取数据

///

///

public void SendGet(EOPERATION op, string name = "")

{

string url = ipAddress + mURLs[op] + "/" + name;

StartCoroutine(Get(url, op, name));

}

///

/// 获取下载进度

///

///

public float GetProgress()

{

if (request == null || !isStartDownload)

return 0;

return request.downloadProgress;

}

private IEnumerator Get(string url, EOPERATION op, string name)

{

if (!string.IsNullOrEmpty(url))

{

using (request = UnityWebRequest.Get(url))

{

isStartDownload = true;

//设置超时 链接超时返回 且isNetworkError为true

request.timeout = 30;

yield return request.SendWebRequest();

isStartDownload = false;

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](name, request.downloadHandler);

}

};

}

}

//private WWW http;

private IEnumerator Post(string url, Dictionary dic, EOPERATION op)

{

if (!string.IsNullOrEmpty(url))

{

WWWForm form = new WWWForm();

foreach (var item in dic)

{

form.AddField(item.Key, item.Value);

}

using (request = UnityWebRequest.Post(url, form))

{

yield return request.SendWebRequest();

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](name, request.downloadHandler);

}

}

}

}

}

然后是改了下读表

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

using System;

using UnityEngine.Networking;

using System.Reflection;

using System.Linq;

using Newtonsoft.Json;

public enum EOPERATION

{

LOGIN = 0,//登录

REGISTER,//注册

COLLEGELIST, //学院

MAJORLIST, //专业

CLASSLIST,//班级

EXISTMAIL,//邮箱重复验证

EXISTNUMBER, //学号重复验证

GETPASSWORD,//忘记密码

ADDSCORE,//添加成绩

DownLoad,

}

///

/// 分发器接口

///

public interface IHander

{

void RegisterMsg(Dictionary> handers);

}

public class UrlPath

{

public EOPERATION operation;

public string path;

}

public class WebWorkData

{

public string ipAddress;

public Dictionary urlPaths;

}

public struct TokenMsg

{

public string name;

public DownloadHandler hander;

}

public class WebWork

{

Dictionary> _handers = new Dictionary>();

public bool isStart { get; private set; }

UnityWebRequest request;

//根据协议号获取地址后缀

WebWorkData webWorkData;

//在这里注册消息返回后分发处理

public void Init()

{

//返回我的解决方案中的所有程序集

Type[] types = AppDomain.CurrentDomain.GetAssemblies()

.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IHander))))

.ToArray();

//相当于

//public static IEnumerable GetType(Type interfaceType)

//{

// foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())

// {

// foreach (var type in assembly.GetTypes())

// {

// foreach (var t in type.GetInterfaces())

// {

// if (t == interfaceType)

// {

// yield return type;

// break;

// }

// }

// }

// }

//}

foreach (var item in types)

{

IHander obj = (IHander)Activator.CreateInstance(item);

obj.RegisterMsg(_handers);

}

//按Json格式序列化

//WebWorkData web = new WebWorkData() { ipAddress = ipAddress, urlPaths = mURLs };

//var json = JsonConvert.SerializeObject(web, Formatting.Indented);

//FileTool.CreateFile(Application.streamingAssetsPath + "/WebData.json", json);

var str = FileTool.BytesToStr(FileTool.ReadFile(Application.streamingAssetsPath + "/WebData.json"));

webWorkData = JsonConvert.DeserializeObject(str);

}

string GetUrl(EOPERATION op, string name = "")

{

return webWorkData.ipAddress + webWorkData.urlPaths[op] + name;

}

///

/// 获取下载进度

///

///

public float GetProgress()

{

if (request == null || !isStart)

throw new Exception(GetType() + "GetProgress()/request==null or !isStart");

return request.downloadProgress;

}

public IEnumerator Get(EOPERATION op, string name)

{

string url = GetUrl(op, name);

if (!string.IsNullOrEmpty(url))

{

using (request = UnityWebRequest.Get(url))

{

isStart = true;

//设置超时 链接超时返回 且isNetworkError为true

request.timeout = 30;

yield return request.SendWebRequest();

isStart = false;

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](new TokenMsg { name = name, hander = request.downloadHandler });

}

};

}

}

public IEnumerator Post(EOPERATION op, Dictionary dic)

{

string url = GetUrl(op);

if (!string.IsNullOrEmpty(url))

{

WWWForm form = new WWWForm();

foreach (var item in dic)

{

form.AddField(item.Key, item.Value);

}

using (request = UnityWebRequest.Post(url, form))

{

isStart = true;

request.timeout = 30;

yield return request.SendWebRequest();

isStart = false;

//结果回传给具体实现

if (request.isHttpError || request.isNetworkError)

{

Debug.Log(request.error);

}

else

{

_handers[op](new TokenMsg { hander = request.downloadHandler });

}

}

}

}

}

表是这个样子

{

"ipAddress": "http://192.168.40.153:8000/",

"urlPaths": {

"LOGIN": "webapi/login/",

"REGISTER": "webapi/register/",

"COLLEGELIST": "user/college/list_combo/",

"MAJORLIST": "user/major/list_combo/",

"CLASSLIST": "user/class/list_combo/",

"EXISTMAIL": "webapi/existemail/",

"EXISTNUMBER": "webapi/existnumber/",

"GETPASSWORD": "webapi/forget_pass/",

"ADDSCORE": "webapi/add_score/",

"DownLoad": "123/"

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值