一般我们与后端对接的时候会用到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<EOPERATION, Action<string, DownloadHandler>> _handers = new Dictionary<EOPERATION, Action<string, DownloadHandler>>();
private string filepath;
bool isStartDownload;
UnityWebRequest request;
//根据协议号获取地址后缀
Dictionary<EOPERATION, string> mURLs = new Dictionary<EOPERATION, string>{
{ 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);
}
/// <summary>
/// 传输数据
/// </summary>
/// <param name="dic"></param>
/// <param name="op"></param>
public void SendPost(EOPERATION op, Dictionary<string, string> dic)
{
//根据协议号获取完整路径
string url = ipAddress + mURLs[op];
StartCoroutine(Post(url, dic, op));
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="op"></param>
public void SendGet(EOPERATION op, string name = "")
{
string url = ipAddress + mURLs[op] + "/" + name;
StartCoroutine(Get(url, op, name));
}
/// <summary>
/// 获取下载进度
/// </summary>
/// <returns></returns>
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<string, string> 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
{
/// <summary>
/// 创建文件
/// </summary>
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<EOPERATION, Action<string,DownloadHandler>> 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<CallBackUser>(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<EOPERATION, Action<string,DownloadHandler>> 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<WebWork>();
we.Init();
we.SendGet(EOPERATION.DownLoad,"chuanjianyinwei.mp4");
}
// Update is called once per frame
void Update () {
Debug.Log(we.GetProgress());
}
}
打开exe开启一个临时资源服务器
记得设置端口号 把配置xml和要下载的文件放入
在主类把上面的地址粘贴过去
挂上脚本运行 进度条显示
资源服务器也有记录
打开项目文件夹也有
改了一下分发器只用实现接口 会根据反射自动初始化实例类 这样不用写那么多初始化代码了
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;
}
/// <summary>
/// 分发器接口
/// </summary>
public interface IHander
{
void RegisterMsg(Dictionary<EOPERATION, Action<string, DownloadHandler>> handers);
};
public class WebWork : MonoBehaviour
{
Dictionary<EOPERATION, Action<string, DownloadHandler>> _handers = new Dictionary<EOPERATION, Action<string, DownloadHandler>>();
bool isStartDownload;
UnityWebRequest request;
//根据协议号获取地址后缀
Dictionary<EOPERATION, string> mURLs = new Dictionary<EOPERATION, string>{
{ 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<Type> 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);
}
/// <summary>
/// 传输数据
/// </summary>
/// <param name="dic"></param>
/// <param name="op"></param>
public void SendPost(EOPERATION op, Dictionary<string, string> dic)
{
//根据协议号获取完整路径
string url = ipAddress + mURLs[op];
StartCoroutine(Post(url, dic, op));
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="op"></param>
public void SendGet(EOPERATION op, string name = "")
{
string url = ipAddress + mURLs[op] + "/" + name;
StartCoroutine(Get(url, op, name));
}
/// <summary>
/// 获取下载进度
/// </summary>
/// <returns></returns>
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<string, string> 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,
}
/// <summary>
/// 分发器接口
/// </summary>
public interface IHander
{
void RegisterMsg(Dictionary<EOPERATION, Action<TokenMsg>> handers);
}
public class UrlPath
{
public EOPERATION operation;
public string path;
}
public class WebWorkData
{
public string ipAddress;
public Dictionary<EOPERATION, string> urlPaths;
}
public struct TokenMsg
{
public string name;
public DownloadHandler hander;
}
public class WebWork
{
Dictionary<EOPERATION, Action<TokenMsg>> _handers = new Dictionary<EOPERATION, Action<TokenMsg>>();
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<Type> 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<WebWorkData>(str);
}
string GetUrl(EOPERATION op, string name = "")
{
return webWorkData.ipAddress + webWorkData.urlPaths[op] + name;
}
/// <summary>
/// 获取下载进度
/// </summary>
/// <returns></returns>
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<string, string> 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/"
}
}
然后分发集成了一个类,这样要添加属性改起来看起来不那么乱吧
地址
https://github.com/1004019267/NetWorkClient