简介:
应公司需求,需要unity的数据与服务器进行对接,主要是信息的上传和拉取,接下来我就简单的介绍一下如果通过IP地址进行信息的通讯,希望可以帮助大家
界面展示:
在这里我就以常见的登录界面为例子向大家进行一个简单的讲述,首先展示界面
在这个界面我们有登录,密码,和IP,所以当我们登录的时候我们需要知道,当前服务器上是否有这个账号,以及我们登录后是否可以从这个地址获取到我们想要的信息
代码展示:
①,首先我们还是需要对应的字段来接受我们所要的信息
/// <summary>
/// HTTP网络请求
/// </summary>
/// <typeparam name="T">泛型</typeparam>
public class HTTPData<T>
{
public int state;//状态码
public string message;//返回消息
public T data;//消息主体
public bool success;//失败或者成功
}
//考核版信息
/// <summary>
/// 考核版用户信息
/// </summary>
public class KaohePlayer
{
//token用户信息,用于服务器识别客户端
public string token;
//学生姓名
public string username;
//学生id
public string id;
//登录的次数
public int loginsTime;
//学生账号-客户端赋值(可能会出现客户端忘记赋值)
public string Account;
//学生密码-客户端赋值(可能会出现客户端忘记赋值)
public string Password;
//班级
public string Class;
}
②,登录的时候向服务器发起请求
//我们再点击登录的时候只需要调用下面代买就可以
NetWorkHttp.Single.KaoheWaitLogin("/v1/arExam/studentLogin", accountInput.text, pwdInput.text, GameManager.Single.mac, WaitImg, errorObj);
public class NetWorkHttp : MonoSingleTon<NetWorkHttp>
{
public string url = "http://192.168.0.112";
public string port = "9527";
/// <summary>
/// 考核模式登录信息
/// </summary>
/// <param name="url"></param>
/// <param name="account"></param>
/// <param name="pwd"></param>
/// <param name="mac"></param>
/// <param name="waitImg"></param>
/// <param name="errorObj"></param>
public async void KaoheWaitLogin(string url, string account, string pwd, string mac, GameObject waitImg,
GameObject errorObj)
{
waitImg.GetComponentInChildren<TextMeshProUGUI>().text = "登陆中,请稍后";
waitImg.SetActive(true);
try
{
string tempU = NetWorkHttp.Single.url + url;
UnityWebRequest request = new UnityWebRequest(tempU, "POST");
request.timeout = 10;
//表单数据
byte[] _data = Encoding.UTF8.GetBytes("account=" + account + "&password=" + pwd + "&macAddr=" + mac);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(_data);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
await request.SendWebRequest();
waitImg.SetActive(false);
if (request.isNetworkError || request.isHttpError)
{
GameManager.Single.isLogining = false;
//服务器连接失败
WrongTips._instance.ShowWrong("服务器连接失败!");
Debug.Log(request.error);
}
else
{
//连接服务器成功
string str = request.downloadHandler.text;
Debug.Log(str);
HTTPData<KaohePlayer> player = JsonMapper.ToObject<HTTPData<KaohePlayer>>(str);
if (player.state != 200)
{
errorObj.SetActive(true);
await Task.Delay(1000);
errorObj.SetActive(false);
}
else
{
GameManager.Single._Player = player.data;
GameManager.Single._Player.Account = account;
GameManager.Single._Player.Password = pwd;
GameManager.Single._Player.token = player.data.token;
Debug.Log(player.data.id);
GameManager.Single._Player.id = player.data.id;
Debug.Log(GameManager.Single._Player.id);
//发送一个指令,来使服务器发送我们需要的信息
KaoheShijuanxinxi("/exam/v1/student/getExamList",GameManager.Single._Player.token,GameManager.Single._Player.id,waitImg);
}
}
}
catch (Exception e)
{
GameManager.Single.isLogining = false;
waitImg.SetActive(false);
Debug.Log(e.Message);
Debug.Log("服务器连接失败");
throw;
}
}
}
?那么登陆成功以后如何获取我们想要的信息呢,在上面我们已经在登录成功后发了一个指令给服务器,接下来我们只需要接受就可以了
/// <summary>
/// 获取考试界面信息和我的试卷信息
/// </summary>
/// <param name="url"></param>
/// <param name="id"></param>
/// <param name="waitImg"></param>
public async void KaoheShijuanxinxi(string url,string token,string id, GameObject waitImg)
{
waitImg.GetComponentInChildren<TextMeshProUGUI>().text = "加载用户信息,请稍后";
waitImg.SetActive(true);
try
{
string tempU = NetWorkHttp.Single.url + url;
UnityWebRequest request = new UnityWebRequest(tempU, "Post");
request.timeout = 8;
//表单数据
byte[] _data = Encoding.UTF8.GetBytes("id=" + id );
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(_data);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.SetRequestHeader("token", token);
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
GameManager.Single.isLogining = false;
//服务器连接失败
WrongTips._instance.ShowWrong("服务器连接失败!");
Debug.Log(request.error);
}
else
{
//用户数据获取成功
string str = request.downloadHandler.text;
HTTPData<List<Information>> testcenters = JsonMapper.ToObject<HTTPData<List<Information>>>(str);
if (testcenters.state != 200)
{
WrongTips._instance.ShowWrong("用户请求数据异常!");
GameManager.Single.isLogining = false;
return;
}
else
{
GameManager.Single.testcenterses = testcenters;
//切换场景
GameManager.Single._loadingData = new LoadingData()
{
_sceneName = "KaoheZhujiemian",
_cb = () =>
{
UIManager.Single.Clear();
}
};
await Task.Delay(1000);
UIManager.Single.Show("UI/LoadingUI");
}
}
waitImg.SetActive(false);
}
catch (Exception e)
{
GameManager.Single.isLogining = false;
waitImg.SetActive(false);
Debug.Log(e.Message);
Debug.Log("服务器连接失败");
throw;
}
}
我们再获取到对应的信息后直接解析,这样我们快就可以使用我们获取到的信息了,其实原理很简单?
收获:
好了,今天又是愉快的和大家一起探究技术的一天,因为工作原因,可能很忙,所以,博客更新不是很勤,以后我会慢慢把我工作中的技术点都分享给大家
|